C# .NET Windows Apps


1. While testing, your C# application froze (became totally non-responsive) unexpectedly. Which of the following is the most likely cause?

A. An exception was thrown by one of the methods in the program
B. Your program entered an infinite cycle
C. Your program tried to access a COM component
D. Your program tried to access a stopped database server
E. Your program tried to access a file it didn't have access to
F. Your program tried to access a server it didn't have access to

>> !
Answer: B

This is a situation that causes a program to stop responding.

An exception generates a runtime error, if not treated within the code.

When the program tries to access a COM component, it either succeeds in it (if it has access permissions to access that component) or not. It is unlikely that trying to access a COM component would freeze your program.

If the program tries to access a file with without having the necessary permissions, an exception is thrown.

This doesn't result in a frozen application, although this might raise an exception.


2. You want to add a private assembly you just created to the Native Image Cache to improve its performance. Which of the following command-line utilities and options adds an assembly to the Native Image Cache?

A. ngen myAssembly.exe
B. gacutil /i myAssembly
C. gacutil /ngen myAssembly
D. ngen /show myAssembly
E. gacutil /ungen myAssembly
F. gacutil /l myAssembly

>> !
Answer: A

The command generates a native image for the mentioned private assembly.

gacutil /i myAssembly installs a shared assembly in the Global Assembly Cache; it doesn't work for private assemblies.

A private assembly can be installed in the GAC by using the ngen command line utility. gacutil does not provide functionality to install private assemblies in the native image cache, although it can uninstall them.

ngen /show myAssembly displays information about myAssembly, provided it is loaded in the native image cache.

gacutil /ungen myAssembly uninstalls myAssembly from the native image generator.

gacutil /l myAssembly doesn't take as a parameter an assembly name. Moreover, if used with no parameters, it just lists the contents of the Global Assembly Cache.


3. You are creating the setup project for your Windows-based application. While configuring the target machine for it, you need to configure its files and shortcuts and specify an additional executable file to run as part of installation. Moreover you use some components that already exist on the target machines, so you don't want to include them into the setup package. When uninstalling your program, these files shouldn't be removed as well. What project views you'll need, and how should you configure the setup project?

A. Use the "File System" and "Custom Actions" views in the Solution Explorer window. For the files that should not be installed, but are to stay on the target computer when the product is uninstalled, set the Exclude property to false and the Permanent property to true
B. For the files that should not be installed, but are to stay on the target computer when the product is uninstalled, set the Vital property to false and the Permanent property to true. Use the "File System" and "Custom Actions" views in the Solution Explorer window
C. Use the "File System" and "Custom Actions" views in the Solution Explorer window. For the files that should not be installed, but are to stay on the target computer after uninstallation of the product, set both the Exclude, and the Permanent properties to true
D. Use the "File System" and "Launch Conditions" views in the Solution Explorer window. For the files that should not be installed, but are to stay on the target computer after uninstallation of the product, set both the Exclude and the Permanent properties to true
E. For the files that should not be installed, but are to stay on the target computer after uninstallation of the product, set both Vital and Permanent properties to false. Use the "File System" and "Custom Actions" views in the Solution Explorer window
F. Use the "File System" and "Launch Conditions" views in the Solution Explorer window. For the files that should not be installed, but are to stay on the target computer when the product is uninstalled, set both Vital and Permanent properties to false

>> !
Answer: C

The File System view configures what files and shortcuts are created in the setup process. The Custom Actions view specifies the additional executable files to run as part of the installation. The Exclude property must be set to true for files required by the application but that should not be added to the setup package (assuming that they already exist on the target computers). The Permanent property specifies whether the file should remain on the target computer even after uninstalling the program.

The Exclude property should be set to true. Setting the Vital attribute to false means that even if installation of the file fails, the installation of the entire project will continue.

You need to specify the executable file to run as part of the installation by using the Custom Actions view. The Launch Conditions view can be used to add install-time checks for conditions that would prevent your application from running properly.

Files that have the Permanent property set to false will be removed from the target computer when the product is uninstalled. Setting the Vital attribute to false means that even if installation of the file fails, the installation of the entire project will continue.

The Launch Conditions view can be used to add install-time checks for conditions that would prevent your application from running properly. Files that have the Permanent property set to false will be removed from the target computer when the product is uninstalled. Setting the Vital attribute to false means that even if installation of the file fails, the installation of the entire project will continue.


4. Your Windows-based application has an assembly you would like to make public by installing it in the Global Assembly Cache. Which of the following steps are to be taken in order to achieve this? (Choose all that apply)

A. Provide a strong name for the assembly using the command line option: sn -v[f] assembly
B. Specify the file containing the public-private key pair using the AssemblyKeyFile or AssemblyKeyName attribute
C. Provide a strong name for your assembly using the command line option : sn -k filename
D. Use the command gacutil /cdl to install the strong-named assembly into the GAC
E. Specify the file containing the public-private key pair using the KeyFileAttribute attribute
F. Use the command gacutil /i to install the strong-named assembly into the GAC

>> !
Answer: B, C & F

gacutil.exe /i installs a strong-named assembly into the Global Assembly Cache.

The name of the file containing the public-private key pair is accepted by the constructors of both AssemblyKeyFile and AssemblyKeyName. Applications deployed in the global assembly cache must have a strong name, or their installation in the GAC will not be allowed. The mentioned command generates a file containing an unique public-private key pair.

"Provide a strong name for the assembly using the command line option: sn -v[f] assembly" is incorrect. This command can be used only to verify an assembly for strong-name signature self-consistency. It cannot be used to provide a strong name for the assembly.

gacutil /cdl deletes the contents of the download cache. To install assemblies in the GAC you have to use the gacutil.exe utility with the /i option.

The file name should be sent to either AssemblyKeyName or AssemblyKeyFile.


5. Being logged in as an administrator, you want to modify certain code access security policies.In order to do this, you need to view both a list of all the assemblies in the Global Assembly Cache, and the code groups and permissions on the User and Enterprise levels. What command-line utilities can you use to accomplish this?

A. Use the .NET Framework Configuration Microsoft Management Console utility for both tasks
B. Use the gacutil.exe utility for both tasks. Type : gacutil.exe /l
C. Use gacutil.exe /l to view code groups and permissions , and caspol.exe -listgroups to view the list of assemblies in the GAC
D. Use caspol.exe -listgroups to view code groups and permissions of the User and Enterprise levels, and gacutil.exe /l to view the list of assemblies in the GAC
E. Use caspol.exe -listgroups to view code groups and permissions of the User level, caspol.exe -enterprise -listgroups to view code groups and permissions on the Enterprise level, and gacutil.exe /l to view the list of assemblies in the GAC
F. Use caspol.exe -user -listgroups to view code groups and permissions for the User level, caspol.exe -enterprise -listgroups to view code groups and permissions on the Enterprise level, and gacutil.exe /l to view the list of assemblies in the GAC.

>> !
Answer: F

Running gacutil /l lists the assemblies in the GAC. Running caspol -listgroups lists the code groups and permissions for the Machine level, since you are logged in as administrator.

You can only view a list of all the assemblies in the GAC (with this particular command). The gacutil program can also be used to install or uninstall them assemblies in or from the GAC. It cannot be used to view details of code groups and permissions.

Running "gacutil /l" lists the assemblies in the GAC, and caspol.exe is for code groups and permissions.

Running caspol.exe -listgroups shows all access groups on the Machine level (since you're logged in as administrator).


6. You have two Windows Forms Application programs that need to use the same private (not shared) assembly. Which of following actions can be applied to achieve the desired result? (Choose all that apply)

A. Add the assembly to the Global Assembly Cache and reference it from the two applications
B. Start the .NET Framework Configuration tool, select Configured Assemblies and click Configure an Assembly. There select the two applications and make them reference the private assembly
C. Place both Windows Forms applications in the same folder, and the private assembly they need to reference in a subfolder name "Private". Edit their configuration files by adding a <probing> element, and set its href attribute to the name "Private"
D. Place both Windows Forms Applications in the same folder as the assembly they need to reference
E. Place both Windows Forms applications in the same folder, and the private assembly they need to reference in a subfolder name "Private." Edit their configuration files by adding a <probing> element, and set its privatePath attribute to the name "Private"
F. Place both Windows Forms applications in the C:\Apps folder, and the private assembly they need to reference in the C:\Private folder. Edit their configuration files by adding a <probing> element which references the C:\Private folder.

>> !
Answer: C, D & E

href attribute is specific to the <codeBase> element, not to <probing>. The private assembly is visible to the two executables if they are placed in the same folder. The private assembly is visible to the two executables if they are placed in the same folder. If the private assembly is located in a subfolder we can use the <probing> element in the configuration file to specify the list of subfolders used to search for the referenced assemblies.

The Configured Assemblies section only works with shared assemblies, and our two Windows Forms applications are not shared assemblies. And if they were shared assemblies, the common assembly they need to access should have been a shared assembly as well (otherwise they couldn't have referenced it).

An assembly added to the Global Assembly Cache is, by definition, a shared assembly, not a private assembly. To be added to the GAC, an assembly also needs a strong name.

Private assemblies cannot be referenced with <probing> if they are not located in the same directory as the Windows Forms executables, or in one of its subdirectories


7. Your Windows Forms application uses many private assemblies. In order to make the application more manageable, you decide to place the private assemblies in their own subfolders. However, after moving the files your application may no longer execute if it can't find the assemblies. If required, how can you make the application find its assemblies without recompiling any code?

A. Configure the href attribute of the <codeBase> configuration element with the help of .NET Framework Configuration tool
B. Configure the href attribute of the <probing> configuration element with the help of .NET Framework Configuration tool
C. Configure the privatePath attribute of the <codeBase> element by editing the application's configuration file to specify where the assembly should be loaded from
D. Configure the privatePath attribute of the <probing> element by editing the application's configuration file to specify where the assembly should be loaded from

>> !
Answer: D

Note that the privatePath attribute cannot be used to specify a directory other than the base directory of your application, followed by, if necessary, subdirectories of the application's base directory. The reason is that private assemblies must be located in the base directory of the application or in one of its subdirectories.

The .NET Framework configuration tool only works with shared assemblies. Private assemblies cannot be turned into shared assemblies without recompiling the code.

The .NET Framework configuration tool only works with shared assemblies. Private assemblies cannot be turned into shared assemblies without recompiling the code. Additionally, the <probing> element doesn't have a href attribute.

There is no privatePath attribute belonging to the <codeBase> element. This attribute belongs to the <probing> element, which can be used to configure a path for a private assembly. If you need to configure the location of a shared assembly, you can use the href attribute of the <codeBase> element.


8. You know that .NET gives the current thread easy access to the application user through the Principal object. Through the Principal object you can access the user's Identity. You can create your own principals by implementing the IPrincipal interface. For which of the following account types the .NET Framework doesn't have built-in functionality for getting the user's identity through an IPrincipal object?

A. Windows accounts
B. Passport accounts
C. ASP.NET cookie-authenticated users
D. SQL Server registered users

>> !
Answer: D

These are managed by SQL Server.

The .NET Framework configuration tool only works with shared assemblies. Private assemblies cannot be turned into shared assemblies without recompiling the code. Additionally, the <probing> element doesn't have a href attribute.

The WindowsPrincipal can be used to get the user's identity through its Identity property.

A PassportAuthenticationEventArgs object is passed to the Authenticate event by a PassportAuthenticationModule. Its Identity property returns the authenticated passport identity, and its User property returns the IPrincipal object associated with the request.

The user's identity can be obtained by reading the Identity property of the IPricipal interface; an IPrincipal object can be obtained, for example, by reading the System.Threading.Thread.CurrentPrincipal.


9. You are creating an Audit class that has the permissions to write information to a log file. The log file is opened like this:

FileStream stream = new FileStream(@"c:\audit.txt",FileMode.Append, FileAccess.Write);

This class is going to be used by external programs that need to write audit information to the log file. The problem is that, even though the Audit class has write access to the audit file, the programs that use the Audit class may not have access to that file. We want our Audit class to have access to the audit.txt log file even if the program that uses it doesn't. Which of the following is correct in regard to this problem?

A. Add the following code in the Audit class, before creating the FileStream object. This will ensure your Audit class has access to the log file, even if the client program doesn't.
FileIOPermission permission = new FileIOPermission
FileIOPermissionAccess.Append,@"c:\audit.txt");permission.Demand();
B. Add the following code in the Audit class, before creating the FileStream object. This will ensure your Audit class has access to the log file, even if the client program doesn't.
FileIOPermission permission = new FileIOPermission
(FileIOPermissionAccess.Append,@"c:\audit.txt");permission.Assert();
C. Using declarative security, add the following attribute to the Audit class. This will ensure your Audit class has access to the log file, even if the client program doesn't.
[FileIOPermission(SecurityAction.Assert, Append=@"c:\audit.txt")]
D. Using declarative security, add the following attribute to the Audit class. This will ensure your Audit class has access to the log file, even if the client program doesn't.
[FileIOPermission(SecurityAction.Demand, Write=@"c:\audit.txt")]
E. If the caller program doesn't have access to the audit file, there's nothing we can do in the Audit class.
F. If the Audit class has access to the audit file we don't need any additional code, even if the caller program doesn't have access to that file.

>> !
Answer: B

Assert is used to enable your code to perform actions that it has permission to do, but its callers might not have permissions to do.

If the caller program doesn't have access to the log file, demanding permission to that file will generate an exception.

Assert is used to enable your code to perform actions that it has permission to do, but its callers might not have permissions to do. This is an example of asserting permissions using declarative security.

If the caller program doesn't have access to the log file, demanding permission to that file will generate an exception.

We can use Assert to get the necessary permission.

We need to use Assert to get the necessary permission.


10. Your application has an assembly for which you want to find out the code groups that it belongs to, as well as their permissions. Moreover, you need to check for the validity of signed file. Which of the following utilities and command line options should you use to obtain the information needed?

A. Use the resolvegroup parameter of the caspol.exe utility to find out the assembly's code groups and their permissions. Use the secutil file to verify the assembly's trust level
B. Use the resolvegroup and resolveperm parameters of the caspol.exe utility to find out about the assembly's code groups and their permissions. Use the chktrust file to verify the assembly's trust level
C. Use the resolvegroup and resolveperm parameters of the caspol.exe utility to obtain information about the assembly's code groups and their permissions, and its trust level
D. Use the chktrust file to achieve all goals
E. Use the resolvegroup and resolveperm parameters of the caspol.exe utility to find out about the assembly's code groups and their permissions. Use the makecert file to verify the assembly's trust level

>> !
Answer: B

This is correct and would obtain all the information needed.

The resolvegroup parameter of the caspol.exe utility won't provide information about the assembly's permissions. It can only be used to list the code groups of an assembly. Moreover, the Secutil tool extracts strong name information or the public key for an X.509 certificate from an assembly and converts this information into a format that can be incorporated into code.

Use chktrust to obtain information regarding the assembly's trust level.

The Certificate Verification tool checks the validity of a file signed with an Authenticode certificate. It cannot be used to view the code groups of an assembly, and neither their permissions. The Certificate Verification tool checks the validity of a file signed with an Authenticode certificate.

The makecert utility creates a public and private key pair for digital signatures and stores it in a certificate file.


11. At certain points in your program you want to change the font used in your Windows Form. When that happens, you want the entire form, including its components, to be resized depending on the dimensions of the new font. However you don't want to allow the user to manually move or resize the form. Which are the properties to be set and to what values should you set them to in order to achieve the desired result? (Choose all that apply)

A. Set the AutoScale property to false and the FormBorderStyle property to none
B. Set the AutoScale property to true and the Locked property to true
C. Set the AutoScale property to true, the Locked property to true, and the FormBorderStyle property to FixedToolWindow
D. Set the FormBorderStyle property to none, and use the GetAutoScaleSize and Size methods of the Form class to resize the window when required
E. Set the Locked property to true, and the FormBorderStyle property to FixedToolWindow, and use the GetAutoScaleSize and Size methods of the Form class to resize the window when required
F. Set the Locked property to true

>> !
Answer: C & D

The FormBorderStyle property controls the appearance of the border of the form. Setting this property to none makes the user unable to move or resize the form. The Size static method of the Form class resizes the window and all its constituent components. This is a sample of code that changes the font of the window and resizes it and its controls accordingly: SizeF szOld = Form.GetAutoScaleSize(this.Font); SizeF szNew = Form.GetAutoScaleSize(new Font("Arial",25)); Form.Scale(szNew.Width/szOld.Width, szNew.Height/szOld.Height); this.Font = new Font("Arial", 25);

The AutoScale property doesn't change the dimensions of the form or its constituent controls at runtime. Setting the FormBorderStyle property to none makes the user unable to move or resize the form.

The Locked property determines whether you can move or resize the control at design time. Setting the Locked property to true does not influence the user's ability to move or resize the control at runtime.

Although setting the FormBorderStyle property to FixedToolWindow will prohibit the user to maximize or minimize the main form, he/she will still be able to move it on the screen. The Locked property determines whether you can move or resize the control at design time, and has no effect at runtime.

Setting the FormBorderStyle property to FixedToolWindow will make the main form unsizable at runtime, but the user will still be able to move it on the screen. The Locked property influences the way the form is seen and worked with at design time.

The Locked property influences neither the form's font size, nor its ability to move or resize at runtime. It is only used at design time.


12. You are creating a Windows Form using the Visual Studio .NET Designer. However you prefer to edit some of its properties directly modifying the code rather than using the designer. You know that setting the Text property of the form results in its caption being changed at runtime. However, you want to set the Text property in the code in such a way that its modified caption can be seen when loading the form in the Visual Studio Designer as well, not only at runtime. Which of the following additions to the code of the Windows Forms file would result in its Caption being changed while the form is opened in the Visual Studio designer? (Choose all that apply)

A.
Change the Text property of the form in the form's Load event handler:
private void Form1_Load(object sender, System.EventArgs e)
{this.Text = "Interesting caption";
}
B.
Change the Text property of the form in the form's constructor:
public Form1()
{InitializeComponent();
this.Text = "Interesting caption";
}
C.
Change the Text property of the form in the InitializeComponent method, like this:
private void InitializeComponent()
{
// ... code here ...
this.Text = new String(new char[]{'I', 'n', 't', 'r', 'e', 's', 't', 'i', 'n', 'g', ' ', 'c', 'a' , 'p', 't', 'i', 'o', 'n'})
// ... code here ...}
D.
Change the Text property of the form in the InitializeComponent method, like this:
private void InitializeComponent()
{
// ... code here ...
this.Text = "Interesting caption";
// ... code here ...}
E.
Change the Text property of the form in the InitializeComponent method, by using a property:
private void InitializeComponent()
{
// ... code here ...
this.Text = caption;
// ... code here ...
}
public string caption
{
get
{
return "Interesting caption";
}
F.
Change the Text property of the form in the InitializeComponent method, by using a property:
private void InitializeComponent()
{
// ... code here ...
string caption = "Interesting caption";
this.Text = caption;
// ... code here...
}

>> !
Answer: C & D

InitializeComponent is the support method for the Visual Studio .NET designer window.

The Visual Studio .NET designer does not analyze the code in Form1_Load event handler, or in any other method except InitializeComponent.

The Visual Studio .NET designer does not analyze the code in the form's constructor, or in any other method except InitializeComponent.

The Visual Studio .NET designer analyzes properties being set in InitializeComponent, but does not execute any other methods or properties.

The Visual Studio .NET designer analyzes properties being set in InitializeComponent, but does not execute any other code except strictly the statements that set directly specified values (literal?) for properties on the form.


13. At certain points in your program you want to change the font used in your Windows Form. When that happens, you want the entire form, including its components, to be resized depending on the dimensions of the new font. However you don't want to allow the user to manually move or resize the form. Which are the properties to be set and to what values should you set them to in order to achieve the desired result?

A. Set the AutoScale property to false and the FormBorderStyle property to none
B. Set the AutoScale property to true and the Locked property to true
C. Set the AutoScale property to true, the Locked property to true, and the FormBorderStyle property to FixedToolWindow
D. Set the FormBorderStyle property to none, and use the GetAutoScaleSize and Size methods of the Form class to resize the window when required
E. Set the Locked property to true, and the FormBorderStyle property to FixedToolWindow, and use the GetAutoScaleSize and Size methods of the Form class to resize the window when required
F. Set the Locked property to true

>> !
Answer: D

The FormBorderStyle property controls the appearance of the border of the form. Setting this property to none makes the user unable to move or resize the form. The Size static method of the Form class resizes the window and all its constituent components. This is a sample of code that changes the font of the window and resizes it and its controls accordingly: SizeF szOld = Form.GetAutoScaleSize(this.Font); SizeF szNew = Form.GetAutoScaleSize(new Font("Arial",25)); Form.Scale(szNew.Width/szOld.Width, szNew.Height/szOld.Height); this.Font = new Font("Arial", 25);

The AutoScale property doesn't change the dimensions of the form or its constituent controls at runtime. Setting the FormBorderStyle property to none makes the user unable to move or resize the form.

The Locked property determines whether you can move or resize the control at design time. Setting the Locked property to true does not influence the user's ability to move or resize the control at runtime.

Although setting the FormBorderStyle property to FixedToolWindow will prohibit the user to maximize or minimize the main form, he/she will still be able to move it on the screen. The Locked property determines whether you can move or resize the control at design time, and has no effect at runtime.

Setting the FormBorderStyle property to FixedToolWindow will make the main form unsizable at runtime, but the user will still be able to move it on the screen. The Locked property influences the way the form is seen and worked with at design time.

The Locked property influences neither the form's font size, nor its ability to move or resize at runtime. It is only used at design time.


14. You have created two Windows Forms in your C# Windows Application. The second is an Inherited Form, deriving from the first form. During runtime, you create two instances of the inherited form and show them on the screen. However, before creating the second instance of the inherited form you add a new TextBox control to the initial form. The code looks like the one below:

InheritedForm form1 = new InheritedForm();
form1.Text = "First";
form1.Show();

TextBox tb = new TextBox();
this.Controls.Add(tb);

InheritedForm form2 = new InheritedForm();
form2.Text = "Second";
form2.Show();

What will the two created forms look like and how will dynamically adding the TextBox control to the original form affect the derived form instances?

A. Both the first inherited form instances will contain the dynamically added textbox
B. Only the first inherited form instance will contain the dynamically added textbox
C. Only the second inherited form instance will contain the dynamically added textbox
D. Neither of the two inherited form instances will contain the dynamically added textbox
E. You cannot create an inherited form instance from the base form
F. You cannot add dynamically created controls to the base form if there are inherited form instances created

>> !
Answer: D

This is correct. We can dynamically add controls to a form by adding them to the form's Controls collection, but this does affect the inherited forms. Only fields and field values created in the source code, available at design time, are inherited.

The dynamically created controls on the base form do not affect the inherited forms.

It is possible to create derived class instances in the base class.

Different form instances are independent and can be individually generated at runtime, no matter from what class they are created.


15. In order to emphasize a portion in the main form of your Windows-based application you need to create a quadrangle filled with a color gradient. In order to achieve this, you will have to use the PathGradientBrush class in conjunction with the GraphicsPath class. Which of the following code snippets successfully achieve the desired result, once added to the Paint event handler of the main form?

A.
Graphics g= e.Graphics;
GraphicsPath gp= new GraphicsPath();

gp.AddLine(10,10,110,15);
gp.AddLine(110,15,100,96);gp.AddLine(100,96,15,110);
gp.CloseFigure();

g.DrawPath(Pens.Black,gp);
PathGradientBrush pgb= new PathGradientBrush(gp);
pgb.CenterColor= Color.White;

pgb.SurroundColors=Color.Blue;
g.FillPath(pgb,gp);
g.DrawPath(Pens.Black,gp);
pgb.Dispose();
B.
Graphics g= e.Graphics;
GraphicsPath gp= new GraphicsPath();

gp.AddLine(10,10,110,15);
gp.AddLine(110,15,100,96);gp.AddLine(100,96,15,110);
gp.CloseFigure();

g.DrawPath(Pens.Black,gp);
PathGradientBrush pgb= new PathGradientBrush(gp);
pgb.CenterColor=Color.White;

pgb.SurroundColors= new Color[]
{
Color.Blue,
Color.Yellow,
Color.Red,
Color.Aqua,
Color.AliceBlue,
};
g.FillPath(pgb,gp);
g.DrawPath(Pens.Black,gp);
pgb.Dispose();
C.
Graphics g= e.Graphics;
GraphicsPath gp= new GraphicsPath();

gp.AddLine(10,10,110,15);
gp.AddLine(110,15,100,96);gp.AddLine(100,96,15,110);
gp.CloseFigure();

Pen blackPen= Pens.Black;
g.DrawPath(blackPen,gp);
PathGradientBrush pgb= new PathGradientBrush(gp);
pgb.CenterColor=Color.White;

pgb.SurroundColors= new Color
[
Color.Blue,
Color.Red,
Color.AliceBlue,
Color.Black,
};

g.FillPath(pgb,gp);
g.DrawPath(blackPen,gp);
blackPen.Dispose();
pgb.Dispose();
D.
Graphics g= e.Graphics;
GraphicsPath gp= new GraphicsPath();

gp.AddLine(10,10,110,15);
gp.AddLine(100,96,15,110);gp.CloseFigure();

g.DrawPath(Pens.Black,gp);
PathGradientBrush pgb= new PathGradientBrush(gp);
pgb.CenterColor=Color.White;

pgb.SurroundColors= new Color[]
{
Color.Blue,
Color.Yellow,
Color.Red,
Color.Aqua,
};

g.FillPath(pgb,gp);
g.DrawPath(Pens.Black,gp);
pgb.Dispose();
E.
Graphics g= e.Graphics;
GraphicsPath gp= new GraphicsPath();

gp.AddLine(10,10,110,15);
gp.AddLine(100,96,15,110);gp.CloseFigure();

g.FillRectangle(Brushes.White, this.ClientRectangle);
g.DrawPath(Pens.Black,gp);
PathGradientBrush pgb= new PathGradientBrush(gp);
pgb.CenterColor=Color.White;

pgb.SurroundColors=Color.Blue;

g.FillPath(pgb,gp);
g.DrawPath(Pens.Black,gp);
pgb.Dispose();

>> !
Answer: D

Results in a quadrangle filled with a color gradient will not work. Note that if we add two segments that are not joined, the GraphicsPath class will automatically add a segment to join them. In our case, the two lines added explicitly by the AddLine method will be automatically joined together. The final shape will be formed when the CloseFigure() method is called on the GraphicsPath instance.

The SurroundColors property needs to be passed an array of colors.

The SurroundColors property cannot be set to an array that contains more colors than there are segments in the GraphicsPath object. Since in the GraphicsPath object there are 4 segments and the array that is passed to the SurroundColors property has 5 colors, this code will result in an exception being thrown at runtime.

An exception will be raised if the blackPen object was not explicitly created. It cannot be explicitly disposed.

The SurroundColors property needs to be passed an array of colors. Therefore this code will result in an exception being thrown.


16. In order to customize the user interface of your Windows-based application you want to emphasize some of the controls with style border. Which of the following code snippets successfully create a hatch-style bordered rectangular?

A.
Brush b= new Brush(Color.Black);
Pen p= new Pen(b,8);
g.DrawRectangle(p,15,15,70,70);
b.Dispose();
p.Dispose();
B.
Pen p= new Pen(Color.Red,8);
HatchBrush hb= new HatchBrush(p,HatchStyle.Cross,Color.Black,Color.Red);
g.DrawRectangle(hb,15,15,70,70);
hb.Dispose();
p.Dispose();
C.
Graphics g=e.Graphics;
HatchBrush hb= new HatchBrush(HatchStyle.Cross,Color.Red,Color.Black);
Pen p= new Pen(hb,8);
g.DrawRectangle(p,15,15,70,70);
hb.Dispose();
p.Dispose();
D.
Pen p= new Pen(Color.Red,8);
Brush h= new Brush(p);
g.DrawRectangle(h,15,15,70,70);
hb.Dispose();
p.Dispose();
E.
Pen p= new Pen(Color.Red,8);
LinearGradientBrush lgb= new LinearGradientBrush(p,Color.Black,Color.White);
g.DrawRectangle(lgb,15,15,70,70);
hb.Dispose();
p.Dispose();

>> !
Answer: C

There are 4 overloaded Pen constructors, expecting either a Color or a Brush object and an optional integer specifying the pen's width. The code snippet above draws a hatch-style bordered rectangle.

Brush is an abstract class and cannot be instantiated.

There is no overloaded method for HatchBrush taking a Pen argument. You should create a Pen taking a Brush argument in the constructor, in order to create the rectangular.

An instance of the abstract class Brush cannot be created. Moreover, no Brush constructor takes a Pen argument. You should use a Pen constructor taking a Brush type argument in order to create the rectangular.

There is no overloaded method for LinearGradiendBrush taking a Pen argument. You should create a Pen taking a Brush argument in the constructor.


17. Your Windows application must provide a user interface to make it easier for the user to select various items. To accomplish this, you populate the form with several checkboxes. The problem is that before the user checks a checkbox for the first time, that checkbox must appear checked but grayed out. Once the user checks the box, it shouldn't appear grayed out any more ever again. From that point on, the only approved states should be checked and unchecked (1->3 answers may make up the correct one) Which properties should you set on the checkboxes to achieve the specified functionality?

A. Set the ThreeState property to true, and CheckState to Indeterminate
B. Set the ThreeState property to false and the CheckState property to Indeterminate
C. Set the ThreeState property to false, the CheckState property to indeterminate and the Checked property to false
D. Set the ThreeState property to true and the Checked property to Indeterminate
E. Set the ThreeState property to true and the Checked property to true
F. Set the ThreeState property to false and the Checked property to true

>> !
Answer: B

This is correct and it results in having the checkbox grayed only in the beginning. If the ThreeState property is false the checkbox should be either in Checked or Unchecked mode. However the initial value of the checkbox can be set to Indeterminate by setting the ChekState property. When CheckState is Indeterminate the Checked property is always true.

The ThreeState property controls whether or not the user can select the indeterminate state of the checkbox. If it is set to true, when the checkbox is clicked its value is set to one of the three states: Checked, Unchecked or Indeterminate. The CheckState property of the checkbox specifies the initial check state of the checkbox.

When CheckState is Indeterminate, Checked is automatically true. The Checkbox doesn't support a state in which it is grayed out and unchecked.

The Checked property indicates whether the checkbox is checked or unchecked and can only be set to true or false.

Setting the ThreeState property to true and the Checking property to true will mean the checkbox isn't initially grayed out. Moreover, setting the ThreeState property to true allows the CheckBox to have an Indeterminate state when clicked.

Once the Checked property is set to true, the CheckState is also automatically set to Checked.


18. The user of your application will have to choose at some point between a number of choices, without the possibility of typing a new option (the control should not be editable). For this purpose you'd like to put on your form a control that could select an item if the user typed its first letter. Which control should you add to your form, what properties should you configure and to what values should you set them to? (Choose all that apply)

A. Add a ListBox control on your Form. Set its SelectionMode property to One and handle its KeyPress event to analyze the typed keys
B. Add a ComboBox to your form. Set its DropDownStyle property to Simple and handle its TextChanged or KeyPress events
C. Add a ComboBox to your form. Set its DropDownStyle property to DropDownList
D. Add a ListBox to your form. Set its SelectionMode property to None and its DropDownStyle property to DropDownList
E. Add a ListBox to your form. Set its DropDownStyle property to DropDown
F. Add a ComboBox to your form. Set its DropDownStyle property to DropDown

>> !
Answer: A & C

Although it's simpler to use a ComboBox because its provided functionality, we can simulate the behavior by handing the KeyPress event. The code in the KeyPress event handler would look like this:
if (e.KeyChar=='e')
{
listBox1.Text = "Europe";
e.Handled = true;
}
With this code, if the ListBox has an element named "Europe", that element will be automatically selected when the user presses the 'e' key.

Setting the DropDownStyle of the ComboBox to DropDownList will make the ComboBox automatically select the element which starts with the typed key(s).

The TextChanged or KeyPress events can be handled, but strictly for achieving the word-completion functionality is much simpler to set the DropDownStyle to DropDownList, in which case you wouldn't need to manually handle any event. When DropDownStyle is set to Simple, the ComboBox permits the user to type a new entry without choosing from the existing ones.

Setting the ListBox's SelectionMode property to None indicates that the ListBox should be unselectable. Additionally, there is no DropDownStyle property to be supported by the ListBox control.

The ListBox control does not support a DropDownStyle property.

While in DropDown mode, the ComboBox is editable. Moreover, it doesn't automatically complete the words when the first letter is typed.


19. For the user interface of your Windows Forms application you decide to group its controls using a GroupBox and a Panel. Which of the following scenarios can be correctly implemented using the GroupBox and Panel containers?

A. Set a caption text for the GroupBox and Panel controls by setting their Text property. Also, you make the Panel scrollable by setting its AutoScroll property to true.
B. Set a caption text for the GroupBox control by setting its Text property. Also, you make the Panel and GroupBox controls scrollable by setting their AutoScroll property to true.
C. Set a caption text for the Panel control by setting its Text property. Also, make the GroupBox scrollable by setting its AutoScroll property.
D. Set a caption text for the GroupBox and Panel controls by setting their Text property. Set the BorderStyle property of the Panel to FixedSingle in order to make its frame visible, and of the GroupBox to None in order not to view its frame.
E. Set a caption text for the GroupBox control by setting its Text property. Set the AutoScroll property of the Panel to true and the BorderStyle of the Panel to FixedSingle in order to make its frame visible.
F. Set the BorderStyle property of the Panel to FixedSingle in order to make its frame visible, and of the GroupBox to None in order not to view its frame.Set the AutoScroll property of the Panel to true.

>> !
Answer: E

GroupBox supports the Text property. The Panel supports the BorderStyle and AutoScroll properties.

The Panel does not have the ability to display caption text.

The GroupBox does not support scroll bars (thus, it doesn't support the AutoScroll property).

The Panel does not have the ability to display caption text. You may set the BorderStyle property of the Panel in order to view its limits, but this property is not supported by the GroupBox control.

The Panel by default does not display a frame .You may set the BorderStyle property of the Panel in order to view its limits, but this property is not supported by the GroupBox control.


20. Your application has a user interface that uses all kinds of controls, including a textbox. When the TextBox control has focus, pressing the Tab key should insert a tab character instead of moving the focus to the next control. What property or properties should be set on the TextBox in order to achieve this?

A. Set the AcceptTab and MultiLine properties of the textbox to true
B. Set the TabStop property of the TextBox to false
C. Set the TabStop property to false and the MultiLine property to true
D. Set the AcceptTab property to true
E. Set the MultiLine and AcceptTab properties to false, and TabStop property to true
F. Set the AcceptTab, Multiline and TabStop properties to false

>> !
Answer: A

This will accomplish the requirements. The AcceptTab property can be set for a textbox only if that textbox were a Multiline.

If AcceptTab is false, pressing the Tab key moves the focus to the next control.

Setting the TabStop property of the TextBox to false would work if the textbox was a Multiline textbox and if all the other controls on the form had the TabStop property set to false.

Setting the TabStop property to false and the MultiLine property to true would work if all the other controls on the form had the TabStop property set to false.

The AcceptTab property only works for Multiline textboxes. If AcceptTab is false, pressing the Tab key moves the focus to the next control.


21. While working at creating the user interface for an accounting program, you need to create a form which needs to be populated to a variable number of textboxes, based on user input.You decide the most efficient implementation would be to create a generic method which takes as a parameter the number of textboxes and places them on the form. Which of the following implementations of the AddControls method are correct, and place on the form a number of textboxes specified by the controlsCount parameter? (Choose all that apply)

A.
public void AddControls(int controlsCount)
{
Control[] arr = new Control[controlsCount];

for (int i=0;i {
arr[i] = new TextBox();
arr[i].Text = i.ToString();
arr[i].Left = i * 10;
arr[i].Top = i * 20;
arr[i].Multiline = true;
this.Controls.Add(arr[i]); }
}
B.
public void AddControls(int controlsCount)
{
TextBox[] arr = new TextBox[controlsCount];

for (inti=0;i {arr[i] = new TextBox();
arr[i].Text = i.ToString();
arr[i].Left = i * 10;
arr[i].Top = i * 20;
arr[i].Multiline = true;
this.Controls.AddRange(arr[i]);
}
}
C.
public void AddControls(int controlsCount)
{ TextBox[] arr = new TextBox[controlsCount];
for (int i=0;i {
arr[i] = new TextBox();
arr[i].Text = i.ToString();
arr[i].Left = i * 10;
arr[i].Top = i * 20;
arr[i].Multiline = true;
}
this.Controls.AddRange(arr);
}
D.
public void AddControls(int controlsCount)
{ TextBox[] arr = new TextBox[controlsCount];
for (int i=0;i {
arr[i] = new TextBox();
arr[i].Text = i.ToString();
arr[i].Left = i * 10;
arr[i].Top = i * 20;
arr[i].Multiline = true;
this.Controls.Add(arr);
}}
E.
public void AddControls(int controlsCount)
{ TextBox[] arr = new TextBox[controlsCount];

for (int i=0;i {
arr[i] = new TextBox();
arr[i].Text = i.ToString();
arr[i].Left = I * 10;
arr[i].Top = I * 20;
arr[i].Multiline = true;
this.Controls.Add(arr[i]);
}
}
F.
public void AddControls(int controlsCount)
{ TextBox[] arr = new TextBox[controlsCount];

for (int i=0;i {
arr[i] = new TextBox();
arr[i].Text = i.ToString();
arr[i].Left = I * 10;
arr[i].Top = I * 20;
arr[i].Multiline = true;
this.Controls.AddTo(I,Arr[i]);
}
}

>> !
Answer: C & E

Both of these are correct and they will place on the form a number of textboxes specified by the controlsCount parameter.

arr[i] is a Control object, and the Control object doesn't support the Multiline property. The Multiline property is specific to the TextBox control.

The AddRange method takes as a parameter a Control[] object (an array of Control objects), not a Control object.

The Add method receives as a parameter a Control object, not an array of controls.

AddTo is not a property of the ControlCollection object


22. When creating the user interface for a Windows Forms application, you need to know for sure the order in which certain events occur for a Button control. The events you are interested in are: MouseMove, MouseLeave, MouseUp, MouseHover, MouseDown, MouseEnter and Click.You get the mouse pointer over the button, click the button, and then move the pointer out of the button's surface. What of the following is a possible order in which the mentioned events could be triggered, considering that certain events can be triggered more than once? (there is a single correct answer!)

A. MouseEnter MouseMove MouseHover MouseMove MouseHover MouseDown Click MouseUp MouseMove MouseLeave
B. MouseEnter MouseMove MouseHover MouseMove MouseDown MouseUp Click MouseMove MouseLeave
C. MouseEnter MouseHover MouseMove MouseMove MouseDown Click MouseUp MouseMove MouseLeave
D. MouseEnter MouseMove MouseHover MouseDown Click MouseMove MouseUp MouseMove MouseLeave
E. MouseEnter MouseMove MouseMove MouseMove MouseHover MouseDown Click MouseUp MouseMove MouseMove MouseLeave
F. MouseEnter MouseMove MouseMove MouseMove MouseDown Click MouseHover MouseUp MouseMove MouseMove MouseLeave

>> !
Answer: E

MouseEnter is always the first event to be triggered when the mouse enters the visible part of the button. The next to be triggered is MouseMove, which occurs when the mouse moves within the button's surface. MouseHover occurs when the mouse remains stationary inside of the control for an amount of time, and can occur only once if the mouse doesn't leave the surface of the control. MouseDown occurs when the mouse pointer is over the button and a mouse button is pressed. If the mouse button is released while the pointer is still over the button, Click and then MouseUp are triggered, otherwise only MouseUp is triggered. MouseLeave is triggered when the mouse leaves the button.

MouseHover, unlike MouseMove, can only be triggered once while the mouse pointer is over the button.

Click is triggered before MouseUp.

MouseHover can only occur after MouseMove. MouseHover cannot happen between Click and MouseUp.

MouseMove cannot be triggered between Click and MouseUp. MouseUp is always the first event to be triggered after Click.


23. You have decided to create a specialized CheckBox class for your Windows Forms project. This class should be named SmartCheckBox, and derive from CheckBox to inherit its base functionality. However, you want your SmartCheckBox to change its Text property every time when it is clicked, specifying how many times it was clicked. As for the other functionality, SmartCheckBox should behave just like a regular CheckBox. Which of the following SmartCheckBox implementations successfully achieve the desired result? (Choose all that apply)

A.
public class SmartCheckBox: System.Windows.Forms.CheckBox
{
private int clickCount=0;

public SmartCheckBox()
{
this.Text = "Please click me.";
this.Size = new Size(200,20);
}

protected override void OnClick(EventArgs e)
{
clickCount++;
this.Text = String.Format("I was clicked {0} times.", clickCount);

base.OnClick(e);
}
}
B.
public class SmartCheckBox: System.Windows.Forms.CheckBox
{
private int clickCount=0;

public SmartCheckBox()
{
this.Text = "Please click me.";
this.Size = new Size(200,20);
}

protected new void OnClick(EventArgs e)
{
clickCount++;
this.Text = String.Format("I was clicked {0} times.", clickCount);

base.OnClick(e);
}
}
C.
public class SmartCheckBox: System.Windows.Forms.CheckBox
{
private int clickCount=0;

public SmartCheckBox()
{
this.Text = "Please click me.";
this.Size = new Size(200,20);
this.Click += new System.EventHandler(this.OnClick);
}

protected void OnClick(object sender, EventArgs e)
{
clickCount++;
this.Text = String.Format("I was clicked {0} times.", clickCount);
}
}
D.
public class SmartCheckBox: System.Windows.Forms.CheckBox
{
private int clickCount=0;

public SmartCheckBox()
{
this.Text = "Please click me.";
this.Size = new Size(200,20);
this.Click += new System.EventHandler(this.OnClick);
}

protected void OnClick(object sender, EventArgs e)
{
clickCount++;
this.Text = String.Format("I was clicked {0} times.", clickCount);

base.OnClick(sender, e);
}
}
E.
public class SmartCheckBox: System.Windows.Forms.CheckBox
{
private int clickCount=0;
public SmartCheckBox()
{
this.Text = "Please click me.";
this.Size = new Size(200,20);
this.Click += new System.EventHandler(this.OnClick);
}

protected void OnClick(object sender, EventArgs e)
{
clickCount++;
this.Text = String.Format("I was clicked {0} times.", clickCount);

base.OnClick(e);
}
}
F.
public class SmartCheckBox: System.Windows.Forms.CheckBox
{
private int clickCount=0;

public SmartCheckBox()
{
this.Text = "Please click me.";
this.Size = new Size(200,20);
this.Click += new System.EventHandler(this.OnClick);
}

protected void OnClick(object sender, EventArgs e)
{
clickCount++;
this.Text = String.Format("I was clicked {0} times.", clickCount);
}
}

>> !
Answer: A & F

In the first implementation, the SmartCheckBox successfully accomplishes the result by overriding the OnClick event handler method. After implementing the particular functionality, it calls the OnClick method of the base class, which changes the checkbox state from checked to unchecked or the other way round. The second implementation correctly defines your own even handler in the SmartCheckBox class without overriding the OnClick method of the base class.

If we hide, instead of override, the OnClick method of CheckBox, SmartCheckBox.OnClick does not get called when the checkbox is clicked.

If the OnClick method does not call the OnClick method of the base class, then the base event handler is not called and the checkbox state doesn't change when it is clicked.

You should not call base.OnClick if the OnClick method is defined as an event handler in SmartCheckBox, not overriding the OnClick method of the base class. Moreover, the OnClick of the base class receives a single parameter.

You should not call base.OnClick if the OnClick method is defined as an event handler in SmartCheckBox, not overriding the OnClick method of the base class. In this example, when the SmartCheckBox is clicked, the OnClick method in the base class is called twice, resulting in the checkbox state being changed two times. This finally results in the Click event being generated in an endless loop.


24. You want to add a menu to your Windows Application. It should have a single top level menu item "File", having two child menu items "Open" and "Save" separated by a horizontal separator line. Which of the following code snippets successfully create the menu as specified, and then iterates its top level menu items and write their Text properties (that is, "File" in our case) in a label?

A.
MainMenu mainMenu = new MainMenu();

MenuItem student = new MenuItem("Student");
mainMenu.MenuItems.Add(student);

student.MenuItems.Add(new MenuItem("Mary"));
student.BarBreak = true;
student.MenuItems.Add(new MenuItem("John"));

foreach (MenuItem m in mainMenu)
label.Text += m.Text;
B.
MainMenu mainMenu = new MainMenu();

MenuItem student = new MenuItem("Student");mainMenu.MenuItems.Add(student);

student.MenuItems.Add(new MenuItem("Mary"));
student.MenuItems.Add("-");
student.MenuItems.Add (new MenuItem("John"));

foreach (MenuItem m in mainMenu)
label.Text += m.Text;
C.
MainMenu mainMenu = new MainMenu();

MenuItem student = new MenuItem("Student");mainMenu.MenuItems.Add(student);

student.MenuItems.Add(new MenuItem("Mary"));
student.MenuItems.Add("-");
student.MenuItems.Add(new MenuItem("John"));

for (int i = 0; i label.Text += mainMenu.MenuItems[i].Text;
D.
MainMenu mainMenu = new MainMenu();

MenuItem student = new MenuItem("Student");
mainMenu.MenuItems.Add(student);

student.MenuItems.Add(new MenuItem("Mary"));
student.BarBreak = true;
student.MenuItems.Add(new MenuItem("John"));

for (int i = 0; i label.Text += mainMenu.MenuItems[i].Text;

>> !
Answer: C

This solution is correct. Adding the "-" menu item results in a horizontal separator line being added to the menu. The mainMenu.MenuItems list is parsed with the presented code.

MainMenu does not implement the IEnumerable interface and it cannot be used with the foreach C# keyword. Moreover, setting the BarBreak property to true results in adding a vertical line and results in placing the two menu items next to each other, horizontally.

Setting the BarBreak property to true results in adding a vertical line and results in placing the two menu items next to each other, horizontally.


25. You want to implement licensing for a custom control you have just created. If the license is not valid, the control should throw a LicenceException. Which of the following actions achieve the desired results? (Choose all that apply)

A. Apply a LicenseProviderAttribute to your control class.
B. Call the IsValid static method of LicenseManager in the constructor of the control, to make sure a valid license can be granted when the control is instantiated.
C. Create and initialize a new License object in the constructor of the control. Call its IsValid method to check if the license key is valid, and throw a LicenseException if it is not.
D. Call the Validate method of the LicenseManager in the constructor of the control.
E. Apply a LicenseAttribute to the class that uses the control and send the name of the licensing file as a parameter.
F. Call Dispose on any instantiated License object when the license is no longer needed.

>> !
Answer: A, D & F

The LicenseProviderAttribute takes a Type parameter identifying the class that implements the actual licensing validation. The only license provider that ships with the .NET Framework is LicFileLicenseProvider, To create your own license providers you need to inherit from the LicenseProvider class and override the IsKeyValid and GetLicense methods. The Validate method is similar to the IsValid method, with the difference that the Validate method throws a LicenseException exception when it tries to create an instance of the control without a valid license. the final step will release the references to open License objects, and is usually done in the Dispose method of the class. Make sure to first verify if the Licence object is not null before calling the Dispose method on it.

The IsValid method returns a Boolean value that specifies if a valid license can be granted for the specified type. You should use Validate instead, which throws an exception if a valid license cannot be granted for the specified type.

The License class is abstract; it cannot be instantiated.

There is no LicenseAttribute that should be applied to the class that uses your control.


26. You implemented licensing for several controls and you want to produce a .licenses file. To achieve this, you will have to use the lc.exe command line utility. You need to specify the list of modules that contain the licensed components to include in the .licenses file, as well as the output directory in which to put the .licenses file. Which of the following is correct, regarding the way you should use the lc.exe command line utility?

A. Specify the list of modules that contain the licensed components with the option: "/complist:list". Specify the output directory in which to put the .licenses file with the command line option : "/target:target".
B. Specify the list of modules that contain the licensed components with the option: "/i:list" . Specify the output directory in which to put the .licenses file with the command line option: "/target: target".
C. Specify the list of modules that contain the licensed components with the option: "/i:<list>". Indicate the output directory in which to put the .licenses file with the command line option: "/outdir: path".
D. Make sure to specify the list of modules that contain the licensed components with the option: "/target:target" . Indicate the output directory in which to put the .licenses file with the command line option: "/outdir: path".

>> !
Answer: C

This is the correct use of the lc.exe command line utility for ths instance.

The '/target:' command line option should not specify the executable for which the .licenses file is being generated.

The "/complist" option points out to the name of a file that contains the list of licensed components. The "/i" specifies the list of modules that contain the components listed in the "/complist" file. The output directory is indicated with the command line option: "/outdir: path".


27. You added to your form a panel and a groupbox. Each container has a button and a textbox. The four controls are named panelTextBox, panelButton, groupTextBox, groupButton. You set the TabIndex property of the containers and of the controls within them as follows: 0 for the Panel, 1 for the GroupBox, 2 and 4 for the controls within the panel, 3 and 5 for the controls within the GroupBox. The TabStop property for the Panel is set to false, and for the textboxes and buttons is true. What is the order in which the controls will get focus when the Tab key is pressed on the form?

A. panelTextBox; groupTextBox; panelButton; groupButton
B. groupTextBox; panelTextBox; groupButton; panelButton
C. panelTextBox; panelButton; groupTextBox; groupButton
D. groupTextBox; groupButton
E. groupTextBox; groupButton; panelTextBox; panelButton

>> !
Answer: C

The fact that the Tab Index for the Panel is 0, while for the GroupBox is 1 implies the user is allowed to navigate first through all controls on the Panel, then through all controls on the GroupBox. The tab order that is set for the controls in the containers affects the way the focus moves at the container level.

The runtime first checks the order in which tabs are set for the containers. It then navigates though every control on a specific container before passing on to another. The fact that the controls on the Panel have tab indexes of 2 and 4 does not influence the actual order in which the user navigates through the containers. Setting the TabStop property of the Panel to false does not have any effect on the focus the user is allowed to place on the controls in the Panel, since their TabStop property is set to true.

The user will be allowed to navigate first through all controls on the Panel, then through all controls in the GroupBox. The order in which Tab Indexes are set at control level does not influence the containers' tab order.

Setting the TabStop property of the Panel to false does not prevent the user from navigating through the controls on the Panel.

Since the TabIndex of the Panel is a smaller number than the TabIndex of the GroupBox, the user will navigate through the Panel's controls first, and then through the controls in the GroupBox. The fact that the TabStop property of the Panel is set to false (although its TabIndex is set to 0) does not imply the GroupBox's controls are to be navigated through first.


28. You have just created an exception class by deriving it from ApplicationException. When raising this error from your code, you want to provide information regarding the object or application, and the method that caused the exception. Additionally, you want to provide the name of a help file that provides more information about the exception. What should you do in order to achieve these goals?

A. Make sure to set the HelpLink, Source and TargetSite properties of the exception
B. Set the HelpLink and Source properties of the exception to achieve all goals
C. Make sure to set both the HelpLink and TargetSite properties of the exception to achieve the desired goals
D. Make sure to set the HelpLink and Source properties of the TargetSite object to achieve the desired goals
E. Make sure to set both the Source and TargetSite properties of the exception to achieve all goals
F. Make sure to set the Source property and its HelpLink field to achieve all goals

>> !
Answer: B

The HelpLink property must specify the path to a file containing information about the exception, while the Source property specifies the name of the object/application that raised it. The TargetSite property mentions the name of the method that raised the exception, and it is supplied automatically by the .NET runtime.

TargetSite is a read-only property whose value is automatically supplied by the .NET runtime, and it specifies the name of the method that raised the exception. The name of the object or application that raised the exception must be specified by setting the Source property of the exception.

Setting both the HelpLink and Source properties of the exception fulfills the requirements. You cannot set the TargetSite property, for it is set automatically by the .NET runtime.

Setting the Source property would specify the name of the application that raised the exception. However, a path to a file containing additional information will not be provided because the HelpLink property of the exception is not set. In addition TargetSite is a read-only property supplied by the .NET runtime

Setting the Source property would specify the name of the application that raised the exception. However, we should also set the HelpLink property and supply a help file location.


29. In one of the functions of your application you implement a try-catch-finally error handling block. In the try block you make two calls: one to another function of your program (which receives an Int32 parameter), and one to a non-.NET, external function, like in this code example:
try
{
myFunction(123456);
COMServer.COMMethod();
}

You want to handle errors generated by both called functions using a generic code. However, the .NET function you call may raise an exception if the parameter is out of range, and you want to handle this kind of exception separately. Which are the catch blocks that separately catch the exception of the first method, when the parameter is out of range, and the rest of exceptions thrown by both .NET and non-.NET clients?

A.
catch(ArgumentException e){/*...;*/}
catch(ArgumentOutOfRangeException e){/*...;*/}
catch{/*...;*/}
B.
catch(ArgumentOutOfRangeException e){/*...;*/}
catch(ArgumentException e){/*...;*/}
catch(Exception e) {/*...;*/}
C.
catch(ArgumentException e){/*...;*/}
catch{/*...;*/}
D.
catch(ArgumentOutOfRangeException e){/*...;*/}
catch(ArgumentException e){/*...;*/}
catch{/*...;*/}
E.
catch(ArgumentOutOfRangeException e){/*...;*/}
catch(ArgumentException e){/*...;*/}
catch{/*...;*/}
catch(Exception e){/*...;*/}
F.
catch(ArgumentOutOfRangeException e){/*...;*/}
catch(ArgumentException e){/*...;*/}
catch(){/*...;*/}

>> !
Answer: D

Your program is able to take actions depending on the type of the exception that was thrown by the method. Moreover, any non-.NET code exceptions will be caught.

If the second catch is unreachable, then the code won't compile. ArgumentOutOfRangeException derives from ArgumentException.

The code must catch exceptions thrown by non-.NET programs (which don't derive from Exception). A parameterless catch block should be added.

The code must trap an ArgumentOutOfRangeException. If is doesn't, your program will give you the desired results, no matter if it is dealing with the general case in which an inappropriate value is passed in the method's arguments or with the particular case in which that value is out of range.

The code won't compile if there are unreachable catch blocks. The catch blocks should be placed from the most specific to the most general.

catch(ArgumentOutOfRangeException e){/*...;*/}
catch(ArgumentException e){/*...;*/}
catch(){/*...;*/}
is almost there but The correct syntax for the last line of the code snippet should be:catch {/*...;*/}


30. While reviewing the code of a C# application you get to a portion of code like the one below. Because of the circumstances, the code in the try block is likely to generate an ArgumentOutOfRange exception, which you need to be correctly handled.

try
{
//... code that generates an ArgumentOutOfRangeException
throw(new ArgumentOutOfRangeException());
}
catch (ArgumentException e)
{
//... handle ArgumentException errors here
Console.WriteLine("Catch");
goto MyLabel;
}
finally
{
Console.WriteLine("Finally");
}

Console.WriteLine("BeforeLabel");

MyLabel:
Console.WriteLine("End");

Which of the following is correct regarding the listed code snippet?

A. The ArgumentOutOfRangeException is not handled by the catch block. The exception is caught by the .NET Runtime

B. C# does not support goto statements. The code doesn't compile

C. The code demonstrates bad programming practice: because of the goto statement, the code in the finally block doesn't get executed. The output is:
Catch
End

D. The code in the finally block is executed before the execution point moves to the designated label. The program's output is:
Catch
Finally
End

E. The goto keyword is ignored in try, catch and finally blocks. The output of the program is:
Catch
Finally
BeforeLabel
End

F. The goto keyword is ignored in try and catch blocks, resulting in the code in the corresponding label not to get executed. The output of the program is:
Catch
Finally
Before
End

>> !
Answer: D

This code will compile and run OK, but the goto keyword should be avoided because it generally results in hard to maintain code.

The catch block handles the ArgumentOutOfRangeException because ArgumentOutOfRangeException derives from ArgumentException.

C# supports goto statements. The code compiles correctly.

The goto keyword is not ignored in try, catch and finally blocks. The code placed after labels is never bypassed (the labels are simply ignored).


31. Your form consists of a large number of controls, and you want to provide the user with an easy way to access individual help for each of these controls. Which of the following is a valid way of achieving this result (Choose all that apply)

A. Drag a HelpProvider component from the Toolbox to your form. In the Properties Window of the form set the HelpButton property to true and the MaximizeBox and MinimizeBox properties to false. Finally, set the HelpString property of each control on the form.
B. Drag a HelpProvider component from the Toolbox to your form. In the Properties Window of the form set the HelpButton property to true and the MaximizeBox and MinimizeBox properties to true. Finally, set the HelpString property of each control on the form.
C. Drag and drop a HelpProvider component on your form. Set the ToolTip property for each control you want an additional explanation for.
D. Drag and drop a ToolTip component on your form. Set the ToolTip property for each control you want an additional explanation for.
E. Drag a ToolTip component from the Toolbox to your form. In the Properties Window of the form set the HelpButton property to true and the MaximizeBox and MinimizeBox properties to false. Finally, set the HelpString property of each control on the form.
F. Drag a ToolTip component from the Toolbox to your form. In the Properties Window of the form set the HelpButton property to true and the MaximizeBox and MinimizeBox properties to true. Finally, set the HelpString property of each control on the form.

>> !
Answer: A, B & D

The ToolTip class can be used to provide help to users when they place the cursor over a control.

In order for the Help button to appear the MaximizeBox and MinimizeBox properties must be set to false.

In order to enable the HelpString property you need to add a HelpProvider component, not a ToolTip component.

In order to enable the HelpString property you need to add a HelpProvider component, not a ToolTip component.


32. Users of your Windows-based application need to receive additional help information if they request it. Therefore you decided to design your program in such a manner so that it would display information if the user pressed F1 while the form or one of the controls on the form are in focus. Which of the following actions should you take to reach the desired result?

A. Drag and drop a HelpProvider on the form. Set the HelpFile property of the HelpProvider to the help file name, and the HelpKeyword property of each control to set the topic to be looked up in the Help file.
B. Drag and drop a HelpProvider on the form. Set the HelpNamespace property of the HelpProvider to the help file name, and the HelpString property of each control in order to enable both context-sensitive and help file information for the selected control.
C. Drag and drop a HelpProvider on the form. Set the HelpNamespace property of the HelpProvider to the help file name, and the HelpKeyword and HelpNavigator properties of each control to set the topic to be looked up in the Help file.
D. Drag and drop a HelpProvider on the form. Set the HelpFile property of the HelpProvider to the help file name, and the HelpString and HelpNavigator properties of each control to set the topic to be looked up in the help file.
E. Drag and drop a HelpProvider on the form. Set the HelpFile property of the HelpProvider to the help file name. Set the HelpButton property of the form to true, and the HelpString properties of the controls you are interested in.
F. Drag and drop a HelpProvider on the form. Set the HelpNamespace property of the HelpProvider to the help file name, the HelpButton property of the form to true, and the HelpString properties of the controls you are interested in.

>> !
Answer: C

There is no HelpFile property in the HelpProvider object. The HelpNamespace property should be used instead.

The HelpString property is only used for providing Pop-up help.

There is no HelpFile property in the HelpProvider object. The HelpNamespace property should be used instead.The HelpString property is used to display Pop-up Help. HelpKeyword should be used instead, which is used to look up a topic in the help file specified by the HelpNamespace property.

Setting HelpButton and HelpString properties provide Pop-up help if the Maximize and Minimize properties of the form are set to false. However, even if Maximize and Minimize were set to false, the user would still be unable to view information as a result of pressing the F1 key.

The HelpNamespace property of the HelpProvider should be used instead, along with the HelpKeyword and HelpNavigator of each control in the form.


33. Your application works with a database that has a Department data table. You want to populate the DataGrid with sorted and filtered information from that table, and you want to allow the user to enter new data into the grid. To achieve this, you create a DataView object and perform on it the required sort and filter operations. Which of the following code snippets list only the departments with an ID less than 100, and sort them by Name in descending order?

A.
DataTable table = dataset.Tables["Department"];
DataView view = new DataView(table);
view.RowFilter = "DepartmentID<= 100";
view.Sort = "Name DESC";
view.AllowNew = true;
B.
DataTable table = dataset.Tables["Department"];
DataView view = new DataView(table);
view.RowFilter = "DepartmentID<= 100";
view.SortCriteria = "Name";
view.SortOrder = "DESC";
view.AllowNew = true;
C.
DataTable table = dataset.Tables["Department"];
DataView view = new DataView(table);
view.RowFilter = "DepartmentID<= 100, Name DESC";
dataGrid.AllowNew = true;
D.
DataTable table = dataset.Tables["Department"];
DataView view = new DataView(table);
view.RowStateFilter = "DepartmentID<= 100";
view.SortCriteria = "Name, DESC";
dataGrid.AllowNew = true;
E.
DataTable table = dataset.Tables["Department"];
DataView view = new DataView(table);
view.RowFilter = "DepartmentID<= 100";
view.SortCriteria = "Name";view.SortOrder = "DESC";
dataGrid.AllowNew = true;

>> !
Answer: A

The RowFilter property gets or sets the expression used to filter records. The Sort property is used to set the sort criteria.

The DataView class doesn't have SortCriteria and SortOrder properties.

The RowFilter property is only used to filter rows, not to sort them. AllowNew is a property of DataView. By setting it to true, the DataGrid will allow the user to add new rows.

SortCriteria is not a method of the DataView class. RowStateFilter filters row based on their state, not on their value.

The DataView class doesn't have SortCriteria and SortOrder properties. AllowNew is a property of DataView. By setting it to true, the DataGrid will allow the user to add new rows.

AllowNew is a property of DataView. By setting it to true, the DataGrid will allow the user to add new rows. RowStateFilter filters row based on their state, not on their value.


34. You already have a working set of COM components used throughout your enterprise application. You want to code some new components using C#. Which of the following represent a good solution of letting the existing COM components access the newly written .NET assemblies? (Choose all that apply)

A. Use the regsvr32 tool to register the .NET assemblies into the registry, making it visible to the COM components.
B. Use the regasm.exe tool.
C. Make all methods and properties in the .NET assembly to have a void return type.
D. Make sure all the methods, properties, events the COM client would be interested in are public.
E. Make sure you only provide default (empty) constructors in the .NET classes.
F. Make sure you only have parameters with a void or integer return value in the .NET class constructors.

>> !
Answer: B, D & E

regasm.exe registers .NET assemblies into the registry to make them available to the COM runtime. This is a requirement if we want the COM clients to be able to access the mentioned methods, properties and events. COM clients can only create types that have a default (empty) constructor.

The regsvr32 tool is similar to the regasm.exe tool, which creates the registry entries the COM runtime needs to locate and load the components. However, regsvr32 only works for native COM components, and regasm is required for registering .NET

COM supports methods and properties that have a non-void return type.

Constructors are not allowed to have return values.


35. Your C# application needs to make use of a COM component through late binding. The particular class you need to access is BizServer.COMClass. Which of the following actions allow you to make calls to COMClass? (Choose all that apply)

A. Get the type of the class you need to use by using the Type.GetTypeFromProgID method.
B. Create an interop assembly using the Type Library Importer utility, tlbimp.exe.
C. Create a new instance of the needed class using the Activator.CreateInstance method.
D. Use the static method InvokeMember of the Type class to make a call to the COMClass method. Send its parameters as System.Object parameters to the InvokeMember method.
E. Add a reference to BizServer by using the Add Reference menu item.
F. Create an array with the parameters to be passed to the COMClass method you want to call. Send the array as a parameter when calling the instance method InvokeMember of the Type class.

>> !
Answer: A, C & F

We need to obtain a Type object to pass to the System.Activator.CreateInstance method in order to create a new instance of COMClass. Creating a new instance of the needed class using the Activator.CreateInstance method will use the reference generated by Type.GetTypeFromProgID() to create a new instance of the component for us. InvokeMember is an instance method of the Type class used to make calls to methods of the specific type.

This would be needed if you wanted to access the COM component through early binding.

InvokeMember is an instance method of Type.

The Visual Studio.NET can automatically import a COM type library for you using the Add Reference menu item. This will create an interop assembly in the project's output directory. However, this method is used to access the server through early binding.


36. In your C# program, you want to get the system time by making a call to the GetSystemTime() function located in Kernel32.dll. The method is defined like this:

void GetSystemTime(LPSYSTEMTIME lpSystemTime);

The SYSTEMTIME structure is defined like this in the Win32 API:
typedef struct _SYSTEMTIME { WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;

Which of the following actions are required to make a call to the GetSystemTime function of the Win32 API? (Choose all that apply)

A.
Declare a SystemTime struct to hold the system time:
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct SystemTime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
B.
Declare a SystemTime struct to hold the system time:
[StructLayoutAttribute(LayoutKind.Explicit)]
private struct SystemTime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
C.
Declare GetSystemTime like this:
[DllImport("kernel32.dll")]
public extern void GetSystemTime(out SystemTime time);
D.
Declare GetSystemTime like this:
[DllImport("kernel32.dll")]
static extern void GetSystemTime(out SystemTime time);
E.
Retrieve the system time by calling the GetSystemTime external function:
SystemTime systemTime = new SystemTime();
PInvoke(GetSystemTime, null, new object [] {systemTime});
F.
Retrieve the system time by calling the GetSystemTime external function:
SystemTime systemTime = new SystemTime();
GetSystemTime(out systemTime);

>> !
Answer: A, D & F

This is the correct way of getting the system time by using the static GetSystemTime method.

There is no PInvoke function.

When using LayoutKind.Explicit, the exact position in the structure should be specified for each member.

With C#, the DllImport attribute only works with static extern methods.


37. You have created a .NET assembly that needs to be used by an existing COM component. For performance reasons, the .NET assembly should be invoked through early binding. Which of the following command-line utilities allow calling .NET components from COM components through early binding? (Choose all that apply)

A. Aximp.exe
B. Regsvr32.exe
C. TlbImp.exe
D. RegAsm.exe
E. TlbExp.exe

>> !
Answer: D & E

RegAsm loads the assembly information into the registry making it available to COM clients. If the /tlb option is used, it also exports the type library to a

TlbExp inspects and assembly and exports all its public types to a COM type library file.

Aximp is used to import ActiveX controls into .NET projects.

Regsvr32 loads a COM type library into the registry.

Tlbimp is used to import COM components into .NET projects.


38. You are creating an application you intend to deploy in Japan. However, the default input mode should be the same as English entry mode, but the user should be able to switch to IME Mode using the keyboard. Note that a satellite assembly for the Japanese language will be needed as well. Which of the following manages to accomplish the desired results?

A. Set the Localizable property of the form to true. Set the ImeMode property to Off. Set the RightToLeft property of the form to true.
B. Set the ImeMode property of the form to Disable. Set the Language property of the form to Japanese and the Localizable property to true.
C. Set the ImeMode property of the form to On. Additionally, create a resource assembly for the Japanese language by setting the Language property of the form.
D. Set the Language property of the form to Japanese. Set the ImeMode property to Off.
E. Set the Language property of the form to Japanese, the Localizable property to true and the ImeMode property to NoControl.
F. Set the Localizable property of the form to true. Set the ImeMode property to Japanese.

>> !
Answer: D

The ImeMode property turned off means that the object behaves by default the same as English entry mode, but users can turn the IME Mode on by using the keyboard. By setting the Language property of the form to Japanese, a resource (satellite) assembly is created for the Japanese language. The Localizable property is automatically set to true when setting the Language property.

Setting the Localizable property of the form will have no effect whatsoever if the Language property of the form is not set to the language you'd like a resource assembly to be created for. Moreover, the RightToLeft property of the form does not allow the users to insert Japanese characters from a regular keyboard.

Setting the ImeMode property of the form to Disable will prevent the users from turning the IME on from the keyboard.

The scenario specifies the default input mode should be the same as English entry mode, so ImeMode shouldn't be set to ImeMode.On.

NoControl is the default ImeMode setting, where no Japanese characters can be entered.

Setting Localizable to true doesn't generate a satellite assembly. You should set the Language property to Japanese, which generates a separate resource file and automatically sets Localizable to true. The ImeMode enumeration doesn't have a Japanese member.


39. In order to create localized versions of your application, you decide to use resource files. You need to have resource files containing both text and pictures. Which of the following can be used to generate a resources file containing text and pictures?

A. The ResGen.exe command-line utility.
B. The Nmake.exe command-line utility.
C. The ResourceWriter class.
D. The ResGen class.

>> !
Answer: C

This class can be used to add both pictures and text to a resource file.

Resgen cannot be used to create resource files containing pictures.

Nmake cannot be used for creating resource files.

Resgen is a command-line utility that can be used for creating text-only resource files.


40. You want to have a textbox in your form for that each character typed appears twice in the textbox. To implement this functionality you decide to implement the KeyPress event handler for the textbox. For simplicity reasons, you named this event handler OnKeyPress. Which of the following implementations of OnKeyPress accomplishes the goal?

A.
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
sender.Text+=e.KeyChar;
sender.SelectionStart=sender.Text.Length;
}
B.
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
TextBox t=(TextBox)sender;
t.Text+=e.KeyChar;
t.SelectionStart=t.Text.Length;
}
C.
private void OnKeyPress (System.Windows.Forms.KeyPressEventArgs e)
{
TextBox t= (TextBox)sender;
t.Text+=e.KeyChar;
}
D.
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
TextBox t=(TextBox)sender;
t.Text+=e.KeyChar;
t.Text+=e.KeyChar;
t.SelectionStart=t.Text.Length;
}
E.
private void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
TextBox t= (TextBox)sender;
t.Text+=e.KeyChar;
t.Text+=e.KeyChar;
t.SelectionStart=t.Text.Length;
}
F.
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{ sender.Text+=e.KeyChar;
sender.Text+=e.KeyChar;
sender.SelectionStart=sender.Text.Length;
}

>> !
Answer: B

Each character written by the user is inserted twice in the textbox. Because the cursor position is lost when modifying the Text property of the TextBox, we always set it to the last position in the textbox.

You cannot read the Text property on an System.Object object.

An additional parameter is required by the OnKeyPress event handler to specify the object that raised the event. Moreover, after modifying the Text property of the TextBox the cursor position is lost - it should be reset using the SelectionStart property.

If we want each character to appear twice in the textbox, we should add it again only once in the OnKeyPress event handler.

The OnKeyPress event handler requires an additional parameter (object sender) that specifies the object that raised the event. Additionally, if we want each character to appear twice in the textbox, we should add it again only once in the OnKeyPress event handler.

You cannot read the Text property on an System.Object object. Additionally, if we want each character to appear twice in the textbox, we should add it again only once in the OnKeyPress event handler.


41. Your Windows Form contains a Button control named button and a Label control named label. You implemented the Click event handler for the button so that it changes the text in the label:

private void button_Click(object sender, System.EventArgs e)
{
label.Text="a";
}

How should you implement the label_TextChanged event handler so that after clicking the button, the label displayed all the letters of the alphabet in order? (Choose all that apply)

A.
private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter=label.Text[label.Text.Length-1]+1;
if(letter<='z') label.Text+=letter;
}
B.
private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1];
letter++;
if(letter<='z') label.Text+=letter;
}
C.
private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1];
letter++;
if(letter<='z')
{
label.Text+=letter;
button_Click(sender,e);
}
}
D.
private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1];
letter++;
if(letter<='z')
{
label_TextChanged(sender,e);
label.Text+=letter;
}
}
E.
private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1];
letter++;
if(letter<='z')
{
label.Text+=letter;
label_TextChanged(sender,e);
}
}
F.
private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1]+1;
if(letter<='z')label.Text+=letter;
button_Click(sender,e);
}

>> !
Answer: B & E

The first correct answer will result in displaying on the label all the letters of the alphabet, in order, once the user clicked the button. The second correct answer will correctly display the alphabet on the label. The Text_Changed event is fired after a letter has been added to the Text property of the label, so it does not change the way the text on the label is modified. Note there is no need for the Text_Changed event to be fired explicitly, since it is fired anyway when actually changing the Text property of the label by adding to it another letter.

private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter=label.Text[label.Text.Length-1]+1;
if(letter<='z') label.Text+=letter;
}
Will not compile because you cannot add a char variable with an integer.

private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1];
letter++;
if(letter<='z')
{
label.Text+=letter;
button_Click(sender,e);
}
}
results in an infinite cycle because as soon as the click event handler of the button is fired again, the Text property of the label is changed to "a", and the cycle restarts.

private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1];
letter++;
if(letter<='z')
{
label_TextChanged(sender,e);
label.Text+=letter;
}
}
In this case the Text_Changed event is fired again before another letter is added to the text property of the label. This results in an infinite number of label_TextChanged events being fired in cascade.

private void label_TextChanged(object sender, System.EventArgs e)
{
Label label=(Label)sender;
char letter= label.Text[label.Text.Length-1]+1;
if(letter<='z')label.Text+=letter;
button_Click(sender,e);
}
doesn't compile because you cannot add a char variable with an integer.


42. You are developing a simple text-processing application, for which you want to add printing capabilities. Which of the following steps are required to implement printing feature for your application? (Choose all that apply)

A. Implement the QueryPageSettings event handler to make changes required to printer settings that relate to all pages of the document.
B. Use the same routine for printing and painting documents on the screen.
C. Check the PagesLeft property of PrintPageEventArgs to test how many pages are there left to print. PrintDocument will be raising QueryPageSettings events as long as the PagesLeft property has a non-zero value.
D. Implement the QueryPageSettings event handler to make changes required to printer settings that relate to the page being printed at the moment the PrintPage event is called.
E. In PrintPage event handler, set the HasMorePages property of the PrintPageEventArgs to specify whether there are any pages left to print.
F. Use the different routines for printing and painting documents on the screen.

>> !
Answer: D, E & F

The QueryPageSettings event is called before each PrintPage event, and it should make changes related to the page being printed. If the value of this property is a true, the PrintDocument class will continue raising the QueryPageSettings events. Using the different routines for printing and painting documents on the screen offers you the flexibility of dealing differently with printing and painting on the screen tasks. For example, when painting to the screen you use scrollbars to paint only the visible portion, while when printing you add one page at a time.

Using the same routine for printing and painting documents on the screen works for very simple documents, but is too inflexible even for a simple text processing application. For example, when painting to the screen you just use scrollbars to paint the appropriate portion, while when printing you add one page at a time.

There is no PagesLeft property. To check whether there are any more pages left there is a Boolean HasMorePages property. Your code needs to independently keep track of how many times PrintPage has been called in order to determine which page is being printed.

The QueryPageSettings event handler should make changes required to printer settings that relate to just the page being printed when the PrintPage event is called.


43. You developed an UI application. Accessible design is important to you because it enables you to reach more customers. What are the points you'd try to follow in order to improve your application's accessibility? (Choose all that apply)

A. Support standard system size, color, font, and input settings. The application should check the setting of SystemInformation.HighContrast when the application starts. Ideally the application should also respond to the UserPreferenceChanged event.
B. Provide documented keyboard access to all features. Expose the location of the keyboard focus.
C. Make the application work with as many colors as possible. Provide different background low-contrast images for different portions of the interface.
D. Make additional changes to your code so that the menu bar, title bar, borders and status bar to automatically update when Control Panel settings change.
E. Convey information by sound alone.

>> !
Answer: A & B

Supporting the user-chosen system settings provides a consistent user interface (UI) across all applications on the user's system. The UserPreferenceChanged event is raised when system user preferences change, including the HighContrast setting. Providing documented keyboard access to all features and then exposing the location of the keyboard focus allows the user to interact with the application without requiring a pointing device, such as a mouse. It should always be easy to see which part of the application has the focus. This requirement also enables use of the Magnifier and Narrator accessibility aids.

The application should work with the system-supplied colors, especially when in High Contrast mode. There should be no background images, to make the text more readable.

The menu bar, title bar, borders, and status bar will use the system settings anyway, without requiring any additional changes in code.

If your application transmits much information by sound, it should also use other means for providing the same information.


44. You need to dynamically add a TextBox control to a Windows Form, and handle its KeyPress even in order to validate each typed character. The character is considered valid if it is a number; any other kind of typed characters should be ignored and not added to the text box. Which of the following code samples successfully achieves the goals? Hint: don't select more than three answers

A.
private void Form1_Load(object sender, System.EventArgs e)
{
InitializeComponent();
TextBox aTextBox = new TextBox();
aTextBox.KeyPress += new KeyPressEventHandler(ValidateKey);
AddControl (aTextBox, new Point(150,20), new Size(100, 20), "txtNumber");
}
private void AddControl(Control control, Point Location, Size size, string strName)
{
control.Location=Location;
control.Size=size;
control.Name=strName;
this.Controls.Add(control);
}
private void ValidateKey (object sender,System.Windows.Forms.KeyPressEventArgs e)
{
// Validate the typed key
if(!Char.IsNumber(e.KeyChar))
e.Handled=true;
}
B.
private void Form1_Load(object sender, System.EventArgs e)
{
TextBox aTextBox;
InitializeComponent();

aTextBox=new TextBox();
aTextBox.Location=new Point(150,20);
aTextBox.Size=new Size(100,20);
aTextBox.Name="txtNumber";
aTextBox.Multiline=false;
aTextBox.KeyPress+=new KeyPressEventHandler(ValidateKey);

this.Controls.Add(this.aTextBox);
}

private void ValidateKey (object sender,System.Windows.Forms.KeyPressEventArgs e)
{
// Validate the typed key
if(!Char.IsNumber(e.KeyChar))
e.Handled=true;
}
C.
private void Form1_Load(object sender, System.EventArgs e)
{
TextBox aTextBox;
InitializeComponent();

aTextBox=new TextBox();
aTextBox.Name="txtNumber";
this.Controls.Add(aTextBox);

int index = this.Controls.GetChildIndex(aTextBox);
this.Controls[index].Location=new Point(150,20);
this.Controls[index].Size=new Size(100,20);
this.Controls[index].KeyPress+=new KeyPressEventHandler(ValidateKey);
}

private void ValidateKey (object sender,System.Windows.Forms.KeyPressEventArgs e)
{
// Validate the typed key
if(!Char.IsNumber(e.KeyChar))
e.Handled=true;
}
D.
private void Form1_Load(object sender, System.EventArgs e)
{
TextBox aTextBox;
InitializeComponent();

aTextBox=new TextBox();
aTextBox.Name="txtNumber";
this.Controls.Add(aTextBox);

this.Controls["txtNumber"].Location=new Point(150,20);
this.Controls["txtNumber"].Size=new Size(100,20);
this.Controls["txtNumber"].KeyPress+=new

KeyPressEventHandler(ValidateKey); }

private void ValidateKey (object sender,System.Windows.Forms.KeyPressEventArgs e)
{
// Validate the typed key
if(!Char.IsNumber(e.KeyChar))
e.Handled=true;
}
E.
private void Form1_Load(object sender, System.EventArgs e)
{
InitializeComponent();

TextBox aTextBox=new TextBox();
aTextBox.KeyPress+=new KeyPressEventHandler(ValidateKey);
AddControl(aTextBox, new Point(150,20), new Size(35, 20),"txtNumber");
}

private bool ValidateKey (object sender,System.Windows.Forms.KeyPressEventArgs e)
{
// Validate the typed key
if(!Char.IsNumber(e.KeyChar))
return true;
else
return false;
}

private void AddControl(Control control, Point Location, Size size, string strName)
{
control.Location=Location;
control.Size=size;
control.Name=strName;
this.Controls.Add(control);
}
F.
private void Form1_Load(object sender, System.EventArgs e)
{
InitializeComponent();

TextBox aTextBox=new TextBox();
aTextBox.KeyPress+=new KeyPressEventHandler(ValidateKey);
this.Controls.AddRange(aTextBox);
}

private bool ValidateKey (object sender,System.Windows.Forms.KeyPressEventArgs e)
{
// Validate the typed key
if(!Char.IsNumber(e.KeyChar))
return true;
else
return false;
}

>> !
Answer: A & C

In the first correct solution, the TextBox control is dynamically created in the Form1_Load event handler and added to the Controls collection of the form using the AddControl class. There is also implemented the ValidateKey method which handles the KeyPress event of the text box. In the second correct solution, the TextBox control is dynamically created in the Form1_Load event handler and added to the Controls collection of the form. Then we find its index in the Controls collection, and set its other properties by referencing it in the collection.

When adding the textbox to the Control collection of the Form, we can't reference it as a member of the form (using this.aTextBox), since it isn't a public member of the form.

The indexer of the Controls collection takes an integer index, not a string parameter.

All event handlers, including KeyPressEventHandler have no return value. We validate the event by setting the e.Handled property to true in the ValidateKey event handler.

The Controls.AddRange method should receive as a parameter an array of controls, not a control instance.Additionally, all event handlers, including KeyPressEventHandler have no return value. We validate the event by setting the e.Handled property to true in the ValidateKey event handler.


45. You are developing a Windows Forms application whose visual interface should support multiple languages. Which one of the following actions can be implemented in practice and lead to the desired result?

A. Add the AssemblyCulture attribute to the main form to specify the default culture, then set the form's Language property to the languages that should be supported by the application. Edit the automatically generated resource files to set the property string associations for each culture.
B. The form's Language property can be set to a single language at a certain point of time. Set the Localizable property of the form to true, and the Language property to the languages supported by the form. In the generated satellite assemblies, set the AssemblyCulture attribute to the supported cultures, and in the generated resource files edit the property string values.
C. Set the Localizable property of the form to true, and specify the supported languages by modifying its AssemblyCulture attribute in AssemlyInfo.cs.
D. Set the Localizable property of the form to true, and the Language property of each control on the form to the default language of the form. Edit the generated XML resource files to supply string values for all the supported languages, and eventually supply code to change the culture programmatically.
E. Set the Language property of the form to the languages you are interested in, one at a time. Edit the automatically generated resource files to set the property string associations for each culture.

>> !
Answer: E

Each time the Language property is set to a new language, Visual Studio .NET creates a new XML-based resource file for that language. These resource files can be modified to adjust the form for that particular culture.

The main assembly must be of neutral culture, and its AssemblyCulture attribute cannot be set to anything different than the empty string. The form's Language property can be set to a single language at a certain point of time. The AssemblyCulture attribute can only be set to a single culture, in satellite assemblies.

Each time the Language property is set to a new language, Visual Studio .NET creates a new XML-based resource file for that language. It also creates compiled satellite assemblies containing the resources, but the AssemblyCulture attribute cannot be manually set on them since we are not provided with their source code as well.

The controls do not support the Language property. XML resource files are generated when setting the Language property of the form to specific languages, and they only contain string property values for a single culture.


46. You created a custom control to use subsequently in your Windows based applications, and you added to it two properties to change its Color and Text whenever needed.

private string displayText;
private Color textColor;

public Color TextColor
{
get{return textColor;}
set{textColor=value; Invalidate();}
}

public string DisplayText
{
get{return displayText;}
set{displayText=value; Invalidate();}
}

You want to specify the default value for TextColor to Color.Red, and for DisplayText to "My Default Text". Which of the following code snippets successfully manages to make these properties work?

A.
Add a DefaultValueAttribute to DisplayText:

[DefaultValue("My Default Text")]

Add a DefaultValueAttribute to TextColor:

[DefaultValue(Color.Red)]
B.
Add a DefaultValueAttribute to DisplayText:

[DefaultValue("My Default Text")]

Add two methods,ResetTextColor and ShouldSerializeTextColor like this:

public void ResetTextColor()
{
TextColor=Color.Red;
}
public bool ShouldSerializeTextColor()
{
return TextColor!=Color.Red;
}
C.
Add a DefaultValueAttribute to TextColor:

[DefaultValue(Color.Red)]

Add two methods, ResetDisplayText and ShouldSerializeDisplayText like this:

public void ResetDisplayText()
{
DisplayText="My Default Text";
}
public bool ShouldSerializeDisplayText()
{
return DisplayText!= "My Default Text";
}
D.
Add a DefaultValueAttribute to TextColor:

[DefaultValue(Color.Red)]

Add a DefaultValueAttribute to DisplayText:

[DefaultValue("My Default Text")]

Add two methods, ResetDisplayText and ShouldSerializeDisplayText like this:

public void ResetDisplayText()
{
DisplayText="My Default Text";
}

public bool ShouldSerializeDisplayText()
{
return DisplayText!= "My Default Text";
}

Add two methods, ResetTextColor and ShouldSerializeTextColor like this:

public void ResetTextColor()
{
TextColor=Color.Red;
}
public bool ShouldSerializeTextColor()
{
return TextColor!=Color.Red;
}

>> !
Answer: B

There is no way in .NET to specify a color as a parameter attribute. This is why you have to supply the ResetTextColor and ShouldSerializeTextColor methods to enable Visual Studio .NET design-time support for your control. Visual Studio .NET will automatically recognize these methods.

DefaultValue won't work with Color because there is no way in .NET to specify a color as a parameter attribute. An attribute argument must be a constant expression, typeof expression or array creation expression.

You should set either the DefaultValue attribute or the ResetXXX and ShouldSerializeXXX methods, but not both. Also, in .NET you can't specify a color as a parameter attribute.


47. You created a control containing two properties, DisplayText and ControlColor. You set their defaults to Color.Blue for ControlColor and "myText" for DisplayText. The code of the controls looks like this:
private string displayText= "myText";
private Color controlColor;

public Color ControlColor
{
get{return controlColor ;}
set{controlColor = value; Invalidate();}
}

public string DisplayText
{
get{return displayText;}
set{displayText=value; Invalidate();}
}
public void ResetControlColor()
{
ControlColor=Color.Blue;
}

public bool ShouldSerializeControlColor()
{
return ControlColor!=Color.Blue;
}

After writing this custom control, you added it to the form of a Windows Application. In the Properties Window you set the ControlColor property to Red and DisplayText to "myText". Which of the following code snippets correctly describes the way Visual Studio initializes the custom control in the InitializeComponent method of the form, after setting the two properties to the values mentioned above?

A. this.myCustomControl.DisplayText = "myText";
this.myCustomControl.ControlColor = Color.Red;
B. this.myCustomControl.ControlColor = Color.Red;
C. this.myCustomControl.DisplayText = "myText";
D. There is no additional code added to the InitializeComponent method after assigning the new values to ControlColor and DisplayText

>> !
Answer: A

Visual Studio assigns a value for DisplayText because you didn't specify a default value for it using the DefaultValue attribute. It also explicitly assigns a value for ControlColor because the value assigned to it is different than its default value.

Visual Studio also assigns a value for DisplayText because you didn't specify a default value for it using the DefaultValue attribute.

Visual Studio also explicitly assigns a value for ControlColor because the value assigned to it is different than its default value.

Visual Studio assigns a value for DisplayText because you didn't specify a default value for it using the DefaultValue attribute. It also explicitly assigns a value for ControlColor because the value assigned to it is different than its default value.


48. In one of your projects you create a dataset which contains the Categories and Products tables of the Northwind database. The DataSet is populated with this code:
SqlConnection connection = new SqlConnection("server=(local)\\NetSDK;uid=sa;pwd=;database=Northwind");

SqlDataAdapter daAuthors = new SqlDataAdapter("Select * from Categories",connection);
SqlDataAdapter daTitles = new SqlDataAdapter("Select * from Products",connection);

DataSet dataSet = new DataSet();
daAuthors.Fill(dataSet,"Categories");
daTitles.Fill(dataSet,"Products");

connection.Close();

After having the fully populated dataset, at some point in the program you need to display each category along with all its related products. Which of the following code snippets display the categories and all products that belong to them?

A.
dataSet.Relations.Add(new DataRelation("CategoryProducts", "Categories","Products","CategoryID","ProductID"));

foreach(DataRow categoryRow in dataSet.Tables["Categories"].Rows)
{
Console.WriteLine("Category: {0}", categoryRow["CategoryName"]);
foreach(DataRow productRow in
categoryRow.GetChildRows("CategoryProducts"))
Console.WriteLine(" Product: 0}", productRow["ProductName"]);
}
B.
dataSet.Relations.Add(new
DataRelation("CategoryProducts","Categories.CategoryID","Products.CategoryID"))
;
foreach(DataRow categoryRow in dataSet.Tables["Categories"].Rows)
{
Console.WriteLine("Category: {0}", categoryRow["CategoryName"]);
foreach(DataRow productRow in dataSet.Relations["CategoryProducts"].GetChildRows["Categories"])
Console.WriteLine(" Product: {0}", productRow["ProductName"]);
}
C.
DataColumn col1 = dataSet.Tables["Categories"].Columns["CategoryID"];
DataColumn col2 = dataSet.Tables["Products"].Columns["ProductID"];
dataSet.Relations.Add(new dataRelation("CategoryProducts",col1,col2));

foreach(DataRow categoryRow in dataSet.Tables["Categories"].Rows)
{
Console.WriteLine("Category: {0}", categoryRow["CategoryName"]);
foreach(DataRow productRow in dataSet.Relations["CategoryProducts"].GetChildRows["Categories"])
Console.WriteLine(" Product: {0}", productRow["ProductName"]);
}
D.
DataColumn col1 = DataSet.Tables["Categories"].Columns["CategoryID"];
DataColumn col2 = dataSet.Tables["Products"].Columns["CategoryID"];
dataSet.Relations.Add(new DataRelation("CategoryProducts",col1,col2));
foreach(DataRow categoryRow in dataSet.Tables["Categories"].Rows)
{
Console.WriteLine("Category: {0}", categoryRow["CategoryName"]);
foreach(DataRow productRow in dataSet.Relations["CategoryProducts"].GetChildRows["Categories"])
Console.WriteLine(" Product: {0}", productRow["ProductName"]);
}
E.
DataColumn col1 = dataSet.Tables["Categories"].Columns["CategoryID"];
DataColumn col2 = dataSet.Tables["Products"].Columns["CategoryID"];
dataSet.Relations .Add(new DataRelation("CategoryProducts",col1,col2));

foreach(DataRow categoryRow in dataSet.Tables["Categories"].Rows)
{
Console.WriteLine("Category: {0}", categoryRow["CategoryName"]);
foreach(DataRow productRow in
categoryRow.GetChildRows("CategoryProducts"))
Console.WriteLine(" Product: {0}", productRow["ProductName"]);
}
F.
DataColumn col1 = dataSet.Tables["Categories"].Columns["CategoryID"];
DataColumn col2= dataSet.Tables["Products"].Columns["ProductID"];
dataSet.Relations.Add(new DataRelation("CategoryProducts",col1,col2));

foreach(DataRow categoryRow in dataSet.Tables["Categories"].Rows)
{
Console.WriteLine("Category: {0}", categoryRow["CategoryName"]);
foreach(DataRow productRow in categoryRow.GetChildRows("CategoryProducts"))
Console.WriteLine(" Product: {0}", productRow["ProductName"]);
}

>> !
Answer: E

This will display the categories and all products that belong to them.

The relation should be created between the CategoryID columns of both tables.

The DataRelation object is not correctly created. Additionally, getChildRows cannot be called on a DataRelation object. GetChildRows cannot be called on a DataRelation object. Moreover, the relation should be implemented between the CategoryID columns in both tables.

GetChildRows cannot be called on a DataRelation object.

The relation should be implemented between the CategoryID columns in both tables.


49. You have an SQL Server database containing product catalog information for your e-commerce web store. Among other tables, you have two data tables named Department and Category having a One-to-Many relationship (one department can contain more categories). The Department table contains three fields: DepartmentID (primary key), Name and Description. The Category table contains four fields: CategoryID (primary key), DepartmentID (foreign key), Name and Description. Which of the following SQL statements returns the name of each category that belong to the "Flowers" department? (Choose all that apply)

A. SELECT Name FROM Category
LEFT OUTER JOIN Department ON DepartmentID
WHERE Department.Name = 'Flowers'

B. SELECT Name FROM Category
JOIN Department ON DepartmentID
WHERE Department.Name = 'Flowers'

C. SELECT Category.Name FROM Category
JOIN Department ON Category.DepartmentID = Department.DepartmentID
WHERE Department.Name = 'Flowers'

D. SELECT Category.Name IN Category
WHERE DepartmentID =
(SELECT DepartmentID IN Department WHERE Name='Flowers')

E. SELECT Name FROM Category
WHERE DepartmentID IN
(SELECT DepartmentID FROM Department WHERE Name='Flowers')

F. SELECT Category.Name FROM Category
WHERE DepartmentID IN
(SELECT * FROM Department WHERE Name='Flowers')

>> !
Answer: C & E

In the first correct answer, both table columns are specified in the JOIN clause (ON Department.DepartmentID = Category.DepartmentID). Also the column to be retrieved is fully qualified using the table name. Because INNER JOIN is the default type of JOIN, we don't need to explicitly add the INNER keyword. The second correct answer retrieves the correct results using a subquery. Another option would be to simply use "=" instead of IN, but the results are the same.

Two table columns need to be specified when joining two tables (should be ON Department.DepartmentID = Category.DepartmentID). Also, we should use an INNER JOIN instead of an OUTER JOIN. Finally, when using joins, when specifying the columns in the SELECT statement we should fully qualify them with the table name (SELECT Category.Name).

Two table columns need to be specified when joining two tables (should be ON Department.DepartmentID = Category.DepartmentID). Also, when using joins, when specifying the columns in the SELECT statement we should fully qualify them with the table name (SELECT Category.Name).

The correct syntax is SELECT FROM, not SELECT IN.

The inner query should select a single column.


50. You are creating a Windows Forms Application that uses data extracted from a database. Because of the business requirements, you want to retrieve data locally, process it in a disconnected fashion, and then submit the changes back to the database. Which of the following actions you are NOT likely to perform, according to the mentioned scenario?

A. Create a DataSet object and fill it with data from the database.
B. Create a SqlDataReader object and get data from the database with it.
C. Create a SqlConnection object, passing a connection string to its constructor.
D. Create a SqlDataAdapter object.
E. Use DataTable objects.

>> !
Answer: B

The SqlDataReader object provides fast, forward-only, read-only access to data. They offer excellent performance but since they don't store any data locally (they can only see the current reader), and because they require an open connection, they cannot be used for disconnected data access.

The DataSet is at the center of disconnected ADO.NET data access.

Creating a SqlConnection object and passing a connection string to its constructor is required when doing any kind of database operation.

Creating a SqlDataAdapter object is used to populate DataSet objects from the data source. The DataSet is at the center of disconnected ADO.NET data access.

The DataSet has a Tables property which is a collection of DataTables. If you're working with DataSets, certainly you'll also meet DataTables.


51. You are creating an application that needs to access a database named TheCatalog located in the local SQL server instance. Which of the following represents the correct connection string to that database, provided you want to log in using Windows security?

A. address=(local);database=TheCatalog;integrated security=true
B. data source=(local);initial catalog=TheCatalog; trusted_connection=false
C. server=(local);database=TheCatalog;authentication=windows
D. address=(localhost);database=TheCatalog;integrated security=true
E. data source=(localhost);initial catalog=TheCatalog; trusted_connection=false
server=(localhost);database=TheCatalog;authentication=windows

>> !
Answer: A

This is the correct connection string. Note that most fields that appear in the connection string have synonyms; check out MSDN for the complete list.

Trusted_Connection should be true.

There is no Authentication connection string parameter.

The local server address is (local).

The local server address is (local). Also, there is no Authentication connection string parameter.


52. You need to export data from your application to an XML output file. For this you use the XmlTextWriter object, which you initialize like this:
XmlTextWriter xmlWr = new XmlTextWriter(@"c:\profiles.xml", Encoding.ASCII);
xmlWr.Formatting = Formatting.Indented;

Using this XmlTextWriter object you want to populate the c:\profilex.xml file with the following contents:

John Doe

Which of the following code snippets successfully populates the profiles.xml like presented?

A.
xmlWr.WriteStartDocument();
xmlWr.WriteStartElement("profile");
xmlWr.WriteAttributeString("company", "Microsoft");
xmlWr.WriteStartElement("employee");
xmlWr.WriteElementString("name", "John Doe");
xmlWr.WriteStartElement("job");
xmlWr.WriteElementString("title", "Software Engineer");
xmlWr.WriteEndDocument();
xmlWr.Close();
B.
xmlWr.WriteStartDocument();
xmlWr.WriteStartElement("profile");
xmlWr.WriteStartElement("company", "Microsoft");
xmlWr.WriteStartElement("employee");
xmlWr.WriteElementString("name", "John Doe");
xmlWr.WriteStartElement("job");
xmlWr.WriteElementString("title", "Software Engineer");
xmlWr.WriteEndElement();
xmlWr.WriteEndElement();
xmlWr.WriteEndElement();
xmlWr.WriteEndElement();
xmlWr.WriteEndDocument();xmlWr.Close();
C.
xmlWr.WriteStartElement("profile");
xmlWr.WriteAttributeString("company", "Microsoft");
xmlWr.WriteStartElement("employee");
xmlWr.WriteElementString("name", "John Doe");
xmlWr.WriteStartElement("job");
xmlWr.WriteElementString("title", "Software Engineer");
xmlWr.WriteEndElement();
xmlWr.WriteEndElement();
xmlWr.WriteEndElement();
xmlWr.WriteEndDocument();
xmlWr.Close();
D.
xmlWr.WriteStartElement("profile");
xmlWr.WriteAttributeString("company", "Microsoft");
xmlWr.WriteSubElement("employee");
xmlWr.WriteElementString("name", "John Doe");
xmlWr.WriteSubElement("job");
xmlWr.WriteElementString("title", "Software Engineer");
xmlWr.WriteEndElement();
xmlWr.WriteEndDocument();
xmlWr.Close();
E.
xmlWr.WriteStartDocument();
xmlWr.WriteStartElement("profile");
xmlWr.WriteAttributeString("company", "Microsoft");
xmlWr.WriteStartElement("employee");
xmlWr.WriteElementString("name", "John Doe");
xmlWr.WriteStartElement("job");
xmlWr.WriteElementString("title", "Software Engineer");
xmlWr.WriteFullEndElement();
xmlWr.Flush();

>> !
Answer: A

When WriteEndDocument is called all open elements are automatically closed; you can manually close all the elements, but it is not necessary.

Company should be an attribute of , not a separate element.

We should call WriteStartDocument to write the XML declaration.

WriteStartElement should be used instead of WriteSubElement. We should call WriteStartDocument which writes the XML declaration.

The XmlTextWriter should be closed with Close. This also ensures all opened tags are closed. We should call WriteStartDocument which writes the XML declaration.


53. At some point in your application you need to update the data source by initializing and executing a SqlCommand object. Which of the following demonstrate a correct way of executing a SqlCommand on the database?

A.
try { string connString = @"Server=(local)\NetSDK;User ID=sa;Password=;Initial Catalog=MyDatabase";
SqlConnection connection = new SqlConnection(connString);
string sql = "UPDATE Product SET Name='Something' WHERE ProductID=12";
SqlCommand command = new SqlCommand(sql,connection);

connection.Open();
int affected = command.ExecuteNonQuery();
Console.WriteLine("{0} affected rows", affected);
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
finally
{
connection.Close();
}
B.
string connString = @"Server=(local)\NetSDK;User ID=sa;Password=;Initial Catalog=MyDatabase";
SqlConnection connection = new SqlConnection(connString);

string sql = "UPDATE Product SET Name='Something' WHERE ProductID=12";
SqlCommand command = new SqlCommand(sql,connection);

try
{
connection.Open();
int affected = command.ExecuteNonQuery();
Console.WriteLine("{0} affected rows", affected);
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
finally
{
connection.Close();
}
C.
string connString = @"Server=(local)\NetSDK;User ID=sa;Password=;Initial Catalog=MyDatabase";
SqlConnection connection = new SqlConnection(connString);

string sql = "UPDATE Product SET Name='Something' WHERE ProductID=12";
SqlCommand command = new SqlCommand(sql,connection);

try
{
connection.Open();
int affected = command.ExecuteNonQuery();
Console.WriteLine("{0} affected rows", affected);
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
connection.Close();
}
D.
try
{
string connString = @"Server=(local)\NetSDK;User ID=sa;Password=;Initial Catalog=MyDatabase";
SqlConnection connection = new SqlConnection(connString);

string sql = "UPDATE Product SET Name='Something' WHERE ProductID=12";
SqlCommand command = new SqlCommand(sql,connection);
connection.Open();
int affected = command.ExecuteNonQuery();
Console.WriteLine("{0} affected rows", affected);
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
connection.Close();
}

>> !
Answer: B

This is the correct approach. The SqlConnection and SqlCommand objects are created outside the try block, but they are effectively used inside the try block. The connection is closed in the finally block, which is guaranteed to execute no matter what happens.

try
{
string connString = @"Server=(local)\NetSDK;User ID=sa;Password=;Initial Catalog=MyDatabase";
SqlConnection connection = new SqlConnection(connString);
string sql = "UPDATE Product SET Name='Something' WHERE ProductID=12";
SqlCommand command = new SqlCommand(sql,connection);

connection.Open();
int affected = command.ExecuteNonQuery();
Console.WriteLine("{0} affected rows", affected);
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
finally
{
connection.Close();
}
won't work. The SqlConnection object created in the try block is not visible in the finally block. The SqlConnection object should be declared before the try block.

The connection should be closed in a finally block, which is guaranteed to execute.

The connection should be closed in a finally block, which is guaranteed to execute. Additionally, The SqlConnection object created in the try block is not visible in the catch block. The SqlConnection object should be declared before the try block.


54. You are in charge of establishing a test plan for a medium-complexity development project. The two approaches you're considering are the waterfall and evolutionary testing approaches. Which of the following is NOT an advantage of the evolutionary approach over the waterfall approach?

A. It reduces the cost of development because it allows refining the design in early stages of development.
B. It is the best approach for small sized projects. It is also often used for more complex projects.
C. It allows testing individual modules of the application, and start adding new functionality after the existing modules have been tested and approved.
D. It is the approach that constantly delivers a working product.

>> !
Answer: B

The waterfall testing approach is best suited only for small projects; for more complex projects, the evolutionary approach is recommended.

MSDN has a number of things to say about this: "You have low-cost opportunities to reappraise requirements and refine the design, as you understand the application better."

[in evolutionary approach] you develop a modular piece (or unit) of an application, test it, fix it, feel somewhat satisfied with it, and then add another small piece that adds functionality."

"You are constantly delivering a working, useful product. If you are adding functionality in priority order, you could stop development at any time and know that the most important work is completed."


55. For testing and debugging your application you decide to use trace switches, since they provide an easy way to log warnings and errors during development time, and disable them when the application is ready for production. At a certain stage during development, for a certain TraceSwitch object you want to receive all messages corresponding to trace levels LOWER than TraceLevel.Info. To what value should you set the TraceSwitch.Level parameter?

A. TraceLevel.Warning
B. TraceLevel.Off
C. TraceLevel.Verbose
D. 3
E. 4
F. TraceLevel.Error

>> !
Answer: A

This is the third trace switch level (has a value of 2), just before TraceLevel.Info (who equals to 3).

TraceLevel.Verbose is the last (and most verbose) trace level, having a value of 5.

3 corresponds to TraceLevel.Info.

4 corresponds to TraceLevel.Verbose

TraceLevel.Error is the second trace switch level (has a value of 1). TraceLevel.Info is the fourth trace switch level (has a value of 3).


56. You want to write trace information using trace listeners and the TextWriterTraceListener class. Which of the following actions CANNOT be done, if you want the trace information get to the destination point?

A. Make a call to the static method Trace.Start and set Trace.AutoFlush to true, to make sure tracing information gets written to the output media.
B. Create a TextWriterTraceListener object and pass to it a FileStream object pointing to the trace log file.
C. Create a TextWriterTraceListener object and pass to it the name of the trace log file.
D. Add a TextWriterTraceListener object to the Trace.Listeners collection, and write trace information using Trace.WriteLine("Trace message here").
E. Call Trace.Flush or set Trace.AutoFlush to true, otherwise the trace information written through the Trace class will not get written.
F. Directly write trace information using the TextWriterTraceListener object.

>> !
Answer: A

The Trace class does not have a static method named Start. The code doesn't compile.

The constructor of TraceWriterTraceListener has an overload that accepts a FileStream object.

The constructor of TraceWriterTraceListener also accepts a string specifying the trace log file name.

Adding the TraceListener object to the Trace.Listeners collection is required if you want to write tracing information to multiple destinations, using the static methods in the Trace class, like WriteLine.

The underlying encoders will not get flushed unless you call the Flush static method of the Trace class or set Trace.AutoFlush to true.

You can write directly using the TextWriterTraceListener object if you don't want the trace information to get to all the listeners in the Trace.Listeners collection, or if the TextWriterTraceListener object hasn't been added to the Trace.Listeners collection.


57. You are debugging mixed-mode (native and managed) code, and you also want to debug the DLLs your application uses. However you encounter slow performance in debugging operations, such as stepping. What can you do to improve the debugging performance, while still being able to debug the DLLs used by your program?

A. Clear the "Allow property evaluation in variables windows" checkbox in the Debugging section of the Options dialog box in the Tools menu. Set breakpoints on DLLs that are not yet loaded.
B. Check the "Allow property evaluation in variables windows" checkbox in the Debugging section of the Options dialog box in the Tools menu. Set breakpoints on DLLs that are not yet loaded.
C. Specify the names of the DLLs you want to debug (in the Additional DLLs dialog box). Check the "Allow property evaluation in variables windows" checkbox from the Options dialog box in the Tools menu.
D. Specify the names of the DLLs you wanted to debug (in the Additional DLLs dialog box). Clear the "Allow property evaluation in variables windows" checkbox from the Debugging section of the Options dialog box in the Tools menu.

>> !
Answer: A

If you turn off property evaluation in the debugger windows, performance in mixed-mode debugging can increase significantly. Moreover, the way to debug a DLL your application uses is by setting a breakpoint on it before it is loaded.

Allowing property evaluation in variables windows is the main cause of poor performance in debugging operations.

Allowing property evaluation in variables windows is the main cause of poor performance in debugging operations. Additionally, if you want to debug a DLL your application uses, it is enough to set a breakpoint on the DLL before it is loaded. You cannot use the Additional DLL's dialog box, since this dialog box no longer exists in the Visual Studio .NET debugger.

Turning off property evaluation in the debugger windows could enhance the performance of mixed-mode debugging. However, you cannot debug a DLL by specifying its name in the Additional DLLs dialog box, since this dialog box belongs to the Visual C++ 6.0 debugger. In the Visual Studio .NET debugger, you can set a breakpoint on a DLL that is not yet loaded. The Additional DLLs dialog box no longer exists.


58. Your application has errors and you need to debug it. In order to see where the errors come from, while debugging you need to bypass lines or entire blocks of code without letting them to execute at all. Which approach would best suit your purpose?

A. Bypass the code you wouldn't like to execute by using the Set Next Statement function.
B. Bypass the code you wouldn't like to execute by using both Step Over and Step Out functions.
C. Bypass the code you don't want to execute by using the Step Out function.
D. Bypass the code you wouldn't like to execute by using the Run to Cursor function.

>> !
Answer: A

The Set Next Statement function changes the execution point without executing any additional code.

Bypassing the code you wouldn't like to execute by using both Step Over and Step Out functions would cause the bypassed code to execute. This is not a correct approach.

The Step Out command executes all the remaining code of the current function.

Run to Cursor lets the code execute and enters break mode at the selected instruction.


59. You would like to personalize your Windows-based application by placing some graphical elements on your main form. One of the things you would like to draw is a dashed, blue rectangle for which you want to customize the dash style, so that your customized dash pattern would have a cycle of four: a 40-pixel dash, then a 10-pixel space, then a 20-pixel dash, then a 10-pixel space. You want the rectangle drawn with a 2-pixel wide pen. Which of the following code snippets achieve the desired results once inserted in the Paint event handler of your form?

A.
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, this.ClientRectangle);
Pen p = new Pen(Color.Blue,2);
float[] f = {40, 10, 20, 10};
p.DashPattern = f;
g.DrawRectangle(p, 10,10,200,100);
p.Dispose();
B.
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, this.ClientRectangle);
Pen p = Pens.Blue;float[] f = {40, 10, 20, 10};
p.DashPattern = f;
g.DrawRectangle(p, 10,10,200,100);
p.Dispose();
C.
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, this.ClientRectangle);
Pen p = new Pen(Color.Blue,2);float[] f = {20, 5, 10, 5};
p.DashPattern = f;g.DrawRectangle(p, 10, 10, 200, 100);
p.Dispose();
D.
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, this.ClientRectangle);
Pen p = Pens.Blue;float[] f = {20, 5, 10, 5};
p.DashPattern = f;g.DrawRectangle(p, 10,10,200,100);
p.Dispose();

>> !
Answer: C

This is correct, and will result in drawing the requested rectangle.

If the pen's width is set to a value greater than 1 pixel, then the actual length of each dash and space is calculated by multiplying the values specified in the array by the width of the pen. Using this code example, the pattern array produces alternating dashes of length 80 and 40, separated by spaces of length 20.

You cannot dispose the pen if you don't own it. Moreover, if the pen's width is set to a value greater than 1 pixel, then the actual length of each dash and space is calculated by multiplying the values specified in the array by the width of the pen.


60. You need to add an ActiveX control to your C# Windows Forms application. How can you add the ActiveX control to the project using the .NET Framework command line utilities?

A. Use the command line tools aximp.exe and tlbimp.exe First create an interop assembly using tlbimp.exe, and then import the generated wrapper classes into the Visual C# project using aximp.exe.
B. Use the command line tool aximp.exe to generate a wrapper class file with the programmatic identifier of the control used as a filename, and then import the generated file into the Visual C# project.
C. Use the command line tool aximp.exe to generate two wrapper assembly files with the programmatic identifier of the control used as a filename, but with different prefixes.
D. Use the command line tool tlbimp.exe to generate a wrapper assembly file for the ActiveX control.
E. Use the command line tools aximp.exe and tlbimp.exe. Both of them are required to create the wrapper classes that permit integrating ActiveX controls into Windows Forms.
F. Use the regasm.exe command line utility.

>> !
Answer: C

Aximp.exe is used to generate the wrapper assemblies that permit including ActiveX controls into .NET projects. It generates 2 files - one of them is the wrapper assembly that can be also generated with tlbimp, and the second contains a class derived from AxHost that is especially required for integrating ActiveX controls.

Aximp.exe generates 2 wrapper files, not just one. The first file is the same type of interop assembly that tlbimp.exe creates, with the programmatic identifier of the control used as a filename; the second contains the additional wrapper classes derived from AxHost, and uses the same filename with an Ax prefix.

To import ActiveX control into .NET projects we use the aximp.exe utility, which also generates a wrapper class derived from AxHost. The AxHost class wraps ActiveX controls and exposes them as fully featured Windows Forms controls.

Only aximp.exe is required. Tlbimp.exe is used to import regular COM type libraries.

Regasm.exe is the assembly registration tool; it is used to create COM type libraries from .NET assemblies, and we need the reverse process.